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.
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.
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.
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.
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
that won't work for empty lists;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With