0

Im trying to use placeholder strings in my Android Kotlin project. According to the doc i have to use %1$s for a singular placeholder in string resources.

I'm using following method to print messages to the user

fun informUser(@StringRes stringID: Int, vararg params: String) {
    val message = main.getString(stringID, params)
    println("INFORM USER: $message")
    Snackbar.make(rootCoordinatorLayout, message, Snackbar.LENGTH_LONG).show()
}

For the purpose of this example i am using the following string resource:

<string name="test_placeholder">This is a %1$s test</string>

When calling the method like this...

informUser(R.string.test_placeholder, "strange")

...the following output is generated. Which is not the expected result.

I/System.out: INFORM USER: This is a [Ljava.lang.String;@18af58a test
Torhan Bartel
  • 550
  • 6
  • 33

1 Answers1

2

The mistake is in these lines:

fun informUser(@StringRes stringID: Int, vararg params: String) {
    val message = main.getString(stringID, params)
    ...
}

The vararg parameter params is available for use inside your function as an Array<String>. So instead of passing all the params you're receiving along to the getString call one by one, you're passing them in as just a single parameter, an array of strings. What you see substituted into your string resource, [Ljava.lang.String;@18af58a, is the toString representation of that array.

To pass along params as individual parameters to getString, use the spread operator:

val message = main.getString(stringID, *params)
zsmb13
  • 85,752
  • 11
  • 221
  • 226