Hi guys, is it possible to get type from Any? I ne...
# announcements
t
Hi guys, is it possible to get type from Any? I need to check whether Any is Collection<String>. I tried something like
Copy code
inline fun <reified T> isTypeOf(any: Any?): Boolean {
    return any is T
}

val isTypeOf: Boolean = isTypeOf<Collection<String>>(Any)
my Any is ArrayList of String.
d
Generics are erased, so at runtime there is no way to distinguish a
List<String>
from a
List<Any>
, there is only
List
.
t
kotlins reified will not help me either?
d
I don't think so, because they don't allow you to "unpack" the type (i.e. go from
List<String>
to
String
). But I could be wrong on that.
v
println(arrayListOf(Object()) is Collection<String>)
will give compiler error
Cannot check for instance of erased type: Collection<String>
So if it does not work directly, it will most probably not work reified
t
Thank you!
v
Or actually see here: https://pl.kotl.in/jvhB1whOt
Due to the reified type usage the compiler is not smart enough to error out
So it compiles fine, but it returns
true
Because erased types are checked
t
@Vampire The only way is to iterate through Collection and check whether element is String, am I right?
v
That could maybe work, yes
d
That would only tell you if there are strings in the collection. It could still be created as `Collection<Any>`:
Copy code
val collection: MutableCollection<Any> = listOf("Hello World")
val isStringCollection = collection.all { it is String } // true, even though it's not