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

Aar*_*Lee 7 android kotlin

我的科特林代码是

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

不起作用if (t is Array<*>)总是会回来false

该函数的代码getCharacteristicInfo为:

public <T> T getCharacteristicInfo(CameraCharacteristics.Key<T> key) {
    return characteristics.get(key);
}
Run Code Online (Sandbox Code Playgroud)

它是获取相机特性的函数。

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

Ale*_*nov 11

t is Array<*>对于对象数组 ( ) 为 true Array<Whatever>,但对于原始数组(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()
}
Run Code Online (Sandbox Code Playgroud)

(如果t在外部其他地方使用,只需将作业移到外部即可)。

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

is Array<*>, is IntArray, ... -> Arrays.toString(t)
Run Code Online (Sandbox Code Playgroud)

即使智能转换在这种情况下可用(它们不可用)。