6

I'm encountering a strange problem: I've a general function which is used to retrieve resource strings (it's just to avoid writing context.resources.getString() everytime):

protected fun string(@StringRes stringRes: Int, vararg args: String): String = app.getString(stringRes, args) 

worked fine up until now, when I added the varargs to retrieve formatted strings. Simple strings still work fine but when I tried to retrieve a formatted one:

string(R.string.formatted_string, myId)

my string resource:

<string name="formatted_string">#%s</string>

I get some garbage:

#[Ljava.lang.String;@3a59711

expected:

#4848684

the garbage change with the resource I request

It looks a Object identifier.

If I don't use the method it works fine

What is happening here?

Sergio
  • 27,326
  • 8
  • 128
  • 149
jack_the_beast
  • 1,838
  • 4
  • 34
  • 67
  • 2
    What you're seeing is the return value of `String[].toString()`. The function observes its `vararg` arguments as a single argument, which is an array. – Marko Topolnik Jan 15 '19 at 09:44

1 Answers1

13

The solution for you is to use the spread operator *:

fun string(@StringRes stringRes: Int, vararg args: String): String = getString(stringRes, *args)

Variable number of arguments (Varargs)

Sergio
  • 27,326
  • 8
  • 128
  • 149
  • Indeed. See this answer for reference on official documentation regarding this asterisk: https://stackoverflow.com/questions/39389003/kotlin-asterisk-operator-before-variable-name-or-spread-operator-in-kotlin – shkschneider Jan 15 '19 at 09:54
  • thanks, I didn't understood the asterisk was needed in this case. – jack_the_beast Jan 15 '19 at 10:09