Cannot resolve string supplied to vararg parameter in extension function

折月煮酒 提交于 2019-11-30 04:22:17

问题


strings.xml

<string name="my_string">Showing your number: %1$s</string>

ActivityExt.kt

fun Activity.showToast(textResId: Int, vararg formatArgs: String) {
    val text = getString(textResId, formatArgs)
    Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}

MainActivity.kt

val number = 11
showToast(R.string.my_string, number.toString())

Toast with following text is showing:

Showing your number: [Ljava.lang.String;@2cfa3b]

Why this happens?


回答1:


Use the spread operator:

fun Activity.showToast(textResId: Int, vararg formatArgs: String) {
    val text = getString(textResId, *formatArgs)
    Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}

Currently, you're passing an array as the format argument. By using the spread operator you pass the contents of the array as the format argument.




回答2:


You should use the spread operator to pass in the varargs to the getString function:

val text = getString(textResId, *formatArgs)

This is because the type of formatArgs inside the showToast function is Array<String> (there's no vararg type or anything like that), and if you pass that in without the *, you'll only pass a single parameter, which will be the array instead of its contents.



来源:https://stackoverflow.com/questions/44798440/cannot-resolve-string-supplied-to-vararg-parameter-in-extension-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!