【问题标题】:String format and vararg in kotlinkotlin 中的字符串格式和可变参数
【发布时间】:2019-11-16 10:31:14
【问题描述】:

我有以下方法

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

我真正想要完成的是能够将任意数量的指标(1,2,3..) 传递给这样的formatMessages,并且将选择/显示正确的字符串。

【问题讨论】:

    标签: android kotlin android-resources variadic-functions android-context


    【解决方案1】:

    将你的函数修改为:

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

    当然,您需要适当检查指标长度是否至少为 2,以免崩溃。

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

    【讨论】:

    • 所以基本上虽然getString得到了数组,但传入的字符串必须与提供的实际参数个数相匹配?
    • 是的,没错。编译器认识到这一点并要求您匹配字符串资源中的参数数量。 Object... formatArgs 是可变参数,不等于 Object[]
    • 我将indicators: IntArray 更改为vararg indicators: Int,但我仍然遇到同样的错误。这不应该是可以接受的吗?
    • 出于某种原因,编译器不允许您这样做。但是,如果您仍然想强制执行此操作,则可以使用 hacky 方法。这意味着这是不可取的。 fun formatMessagesHack(resourceId: Int, indicators: IntArray): CharSequence { return context.getString(resourceId, indicators) } 这样一来,编译器就不知道你要格式化的具体资源是什么。
    【解决方案2】:

    When we call a vararg-function, we can pass arguments one-by-one, e.g. 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)
    }
    

    如果您需要 indicators 具有类型 IntArray,则必须将其转换:

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

    【讨论】:

      猜你喜欢
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      • 2020-11-23
      • 2014-05-29
      • 2010-10-17
      • 1970-01-01
      相关资源
      最近更新 更多