androidkotlinresourcesvariadic-functionsandroid-resources

Android and Kotlin varargs: formatted strings returns garbage


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?


Solution

  • 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)