如何在Kotlin中检查变量是否为数组

时间:2019-02-20 09:41:53

标签: android kotlin

我的科特琳代码是

val t = cameraController.getCharacteristicInfo(myDataset[position])
if (t is Array<*>) {
     holder.keyValue.text = Arrays.toString(t)
} else {
     holder.keyValue.text = t.toString()
}

无效if (t is Array<*>)始终返回false

函数getCharacteristicInfo的代码为:

public <T> T getCharacteristicInfo(CameraCharacteristics.Key<T> key) {
    return characteristics.get(key);
}

这是获取相机特性的功能。

如何正确检查变量是否为数组?

2 个答案:

答案 0 :(得分:2)

t is Array<*>对于对象数组(Array<Whatever>)为true,但对于基本数组(IntArray等)为false。所以你可能想要

holder.keyValue.text = when(val t = cameraController.getCharacteristicInfo(myDataset[position])) {
    is Array<*> -> Arrays.toString(t)
    is IntArray -> Arrays.toString(t)
    ...
    else -> t.toString()
}

(如果t在其他地方之外使用,只需将分配移到外面即可)。

请注意,这些是不同的Arrays.toString重载,因此您无法编写

is Array<*>, is IntArray, ... -> Arrays.toString(t)

即使在这种情况下(不是)也可以使用智能投射。

答案 1 :(得分:0)

遇到了相同的问题,并使用了isArray中的Class

>>> arrayOf("a","b","c")::class.java.isArray
res1: kotlin.Boolean = true
>>> IntArray(1)::class.java.isArray
res2: kotlin.Boolean = true
>>> Array<String>(1) { "a" }::class.java.isArray
res3: kotlin.Boolean = true
>>> Any::class.java.isArray
res4: kotlin.Boolean = false

注意:如果您的目标不是JVM,则可能不可用。