Search code examples
kotlinarraylistcastingany

Kotlin Check and access a class from List<Any>


How can you check and access adViewClass from the array of Any?

val adViewClass = AddViewClass(name = "an instance")
val elements = listOf("trevor", "john", adViewClass, "0goo")

How to get that adViewClass from list


Solution

  • You can use simple elementAt to get class

    elements.elementAt(2)
    

    elementAt() is useful for collections that do not provide indexed access, or are not statically known to provide one. In case of List, it's more idiomatic to use indexed access operator (get() or []).

    and check class using is

    if (obj is AdViewClass) {
    

    We can check whether an object conforms to a given type at runtime by using the is operator