lbenedetto
lbenedetto

Reputation: 2114

Check type of ArrayList in 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.

Upvotes: 10

Views: 17894

Answers (3)

Kevin Meneses Palta
Kevin Meneses Palta

Reputation: 85

If you want to check the type of a list you can do:

when (list.firstOrNull()) {
   is String -> { /*do something*/ }
   is Int -> { /*do another thing*/ }
   else -> { /*do something else*/ }
}

And if you need to use the list of a certain type you can use:

list.filterInstance</*the type you need*/>()

Hope this works for you.

Upvotes: 7

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

If the list is of one type then you can convert the list to array using: toTypedArray() and after you can then check the type using: isArrayOf

But this would be inefficient since you are converting the list to array, better if you can just directly guess or retrieved the first item of the list.

Upvotes: 0

Alexey Romanov
Alexey Romanov

Reputation: 170745

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.

Upvotes: 4

Related Questions