简体   繁体   中英

String format and vararg in kotlin

I have the following method

fun formatMessages(indicators: IntArray): CharSequence {
    return context.getString(R.string.foo, indicators)
}

And the string is:

<string name="foo">$1%d - $2%d range of difference</string>

I get a complaint from Android Studio that:
Wrong argument count, format string requires 2 but format call supplies 1

What I am really trying to accomplish is to be able to pass to such a formatMessages any number of indicators (1,2,3..) and the proper string would be selected/displayed.

Modify your function to this:

fun formatMessages(indicators: IntArray): CharSequence {
    return context.getString(R.string.foo, indicators[0], indicators[1])
}

But of course you need a proper checking that indicators length is at least 2 so it will not crash.

Reason for this is getString(int resId, Object... formatArgs) runtime will fail because it expects 2 parameters from what is defined in the string resource.

When we call a vararg-function, we can pass arguments one-by-one, eg asList(1, 2, 3), or, if we already have an array and want to pass its contents to the function, we use the spread operator (prefix the array with *):

fun formatMessages(indicators: Array<Object>): CharSequence {
    return context.getString(R.string.foo, *indicators)
}

If you need indicators to have type IntArray , you'll have to convert it:

fun formatMessages(indicators: IntArray): CharSequence {
    return context.getString(R.string.foo, *(Array<Object>(indicators.size) { indicators[it] }))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM