[英]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:我收到来自 Android Studio 的投诉:
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.我真正想要完成的是能够将任意数量的指标(1,2,3..)
传递给这样的formatMessages
,并且将选择/显示正确的字符串。
Modify your function to this:将您的 function 修改为:
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.但当然,您需要适当检查指标长度是否至少为 2,这样它就不会崩溃。
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.原因是getString(int resId, Object... formatArgs)
运行时将失败,因为它需要字符串资源中定义的 2 个参数。
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 *): 当我们调用一个可变参数函数时,我们可以一对一地传递 arguments,例如 asList(1, 2, 3),或者,如果我们已经有一个数组并且想要将其内容传递给 function,我们使用扩展运算符(以 * 为数组前缀):
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:如果您需要indicators
的类型为IntArray
,则必须对其进行转换:
fun formatMessages(indicators: IntArray): CharSequence {
return context.getString(R.string.foo, *(Array<Object>(indicators.size) { indicators[it] }))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.