Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check type of ArrayList in Kotlin

Tags:

kotlin

Kotlin provides Array.isArrayOf() for checking if an array is of a certain type.

It's used like this

if(object.isArrayOf<String>())

And defined like this

/**
 * Checks if array can contain element of type [T].
 */
@Suppress("REIFIED_TYPE_PARAMETER_NO_INLINE")
public fun <reified T : Any> Array<*>.isArrayOf(): Boolean =
    T::class.java.isAssignableFrom(this::class.java.componentType)

But it's only for Array. I need to check ArrayList.

I thought to change the signature like so.

@Suppress("REIFIED_TYPE_PARAMETER_NO_INLINE")
public fun <reified T : Any> ArrayList<*>.isArrayListOf(): Boolean =
    T::class.java.isAssignableFrom(this::class.java.componentType)

but class.java.componentType is specific to Array

How can I check what type of ArrayList I have?

I should clarify, I only care if its one of 3 types, so I don't need a completely open-ended way of checking.

like image 612
lbenedetto Avatar asked Nov 29 '18 19:11

lbenedetto


People also ask

How do I check my data type on Kotlin?

You can use b::class. simpleName that will return type of object as String . You don't have to initialize type of a variable and later you want to check the type of variable.

Is Kotlin ArrayList mutable?

ArrayList is a class that happens to implement the MutableList interface. The only difference is that arrayListOf() returns the ArrayList as an actual ArrayList . mutableListOf() returns a MutableList , so the actual ArrayList is "disguised" as just the parts that are described by the MutableList interface.

What does ?: Mean in Kotlin?

The elvis operator in Kotlin is used for null safety. x = a ?: b. In the above code, x will be assigned the value of a if a is not null and b if a is null . The equivalent kotlin code without using the elvis operator is below: x = if(a == null) b else a.


1 Answers

You can't. Arrays are the only generic type for which this is possible (because they aren't really generic in the same sense, Kotlin just hides it).

The only thing you can do is look at its contents, but of course

  1. that won't work for empty lists;

  2. if a list contains e.g. a String, it could be ArrayList<String>, ArrayList<CharSequence>, ArrayList<Any>, etc.

For this purpose:

I need to direct it into the appropriate Bundle method. bundle.putStringArrayList(), bundle.putIntegerArrayList(), ect

neither should be a problem, I believe.

like image 101
Alexey Romanov Avatar answered Oct 04 '22 21:10

Alexey Romanov