7

My Kotlin code is

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

It is not working. if (t is Array<*>) always returns false.

The code of the function getCharacteristicInfo is:

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

It is a function for getting camera characteristics.

How to properly check if a variable is an array?

5
  • Can you show us the code of getCharacteristicInfo()? Commented Feb 20, 2019 at 9:43
  • Ok. Added it. It it a function getting camera characteristics. Commented Feb 20, 2019 at 9:50
  • It seems t is not actually Array type. Could you edit your code to show type of characteristics and myDataset[position] as well? Commented Feb 20, 2019 at 10:01
  • show complete class Commented Feb 20, 2019 at 10:07
  • Can you show the type of myDataset[position] variable? getCharacteristicInfo returns value of type T related to Key<T> being passed as parameter. myDataset[position] is some kind of Key<T> (indeed, the code compiles) but may be is - e.g. - Key<String> and this forces t to be of type String... Commented Feb 20, 2019 at 14:40

2 Answers 2

11

t is Array<*> is true for object arrays (Array<Whatever>), but false for primitive arrays (IntArray etc.). So you probably want

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

(if t is used outside elsewhere, just move the assignment outside).

Note that these are different Arrays.toString overloads, so you couldn't write

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

even if smart casts were available in this situation (they aren't).

Sign up to request clarification or add additional context in comments.

Comments

1

Faced the same issue and used isArray of the 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

NOTE: That might not be available if your target is not JVM.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.