kotlin 中的字符串格式和可变参数

问题描述 投票:0回答:3

我有以下方法

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

字符串是:

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

我收到 Android Studio 的投诉:

Wrong argument count, format string requires 2 but format call supplies 1

我真正想要完成的是能够传递给这样的

formatMessages
任意数量的指标
(1,2,3..)
并且将选择/显示正确的字符串。

android kotlin android-resources variadic-functions android-context
3个回答
1
投票

将你的函数修改为:

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

但是当然你需要适当检查指标长度至少为 2,这样它就不会崩溃。

原因是

getString(int resId, Object... formatArgs)
运行时会失败,因为它需要字符串资源中定义的 2 个参数。


0
投票

当我们调用可变参数函数时,我们可以一一传递参数,例如asList(1, 2, 3),或者,如果我们已经有一个数组并希望将其内容传递给函数,我们可以使用扩展运算符(在数组前面加上 * 前缀):

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

如果您需要

indicators
具有类型
IntArray
,则必须将其转换:

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

0
投票

不幸的是,Kotlin 的

String.format
函数不直接接受 vararg 参数。我们必须单独传递参数。

© www.soinside.com 2019 - 2024. All rights reserved.