Reputation: 117
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
Upvotes: 1
Views: 878
Reputation: 19220
You can get all instances of a specific class that are in a list using the filterIsInstance(Class<>)
val elements: List<Any> = listOf<Any>("trevor", "john", AdViewClass, "0goo")
val listOfAdViewClass = elements.filterIsInstance(AdViewClass::class.java)
The filtered list will contain all instances of that class in the list.
Upvotes: 4
Reputation: 58772
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
Upvotes: 1