Simple question: I need a set of classes that exte...
# announcements
h
Simple question: I need a set of classes that extend (in java) from a base class so that I can iterate over the set and test an object if it
is Base
. Something along
val clazzes : MutableSet< ???> = ...
and then e.g.
clazzes.forEach { c -> if(obj is c){..}}
. How can I do that?
b
do you have instances? or the just the class types?
if it's instances, you could just have
val instances = MutableSet<Any>
and then
instances.forEach { c -> if (c is Base) { .. } }
if it's types, maybe this would work? not sure how idiomatic/foolproof it is:
Copy code
open class Base

class Sub : Base()

val clazzes = listOf(Int::class, Double::class, Sub::class)

clazzes.forEach { clazz -> if (clazz.supertypes.contains(Base::class.starProjectedType)) println("found subtype") }
h
@bbaldino I have something like this (which is wrong)
Copy code
kotlin
private val myClasses : MutableSet<Class<in FoldingDescriptor>> = mutableSetOf()

  constructor(expand: Boolean, vararg classes: Class<in FoldingDescriptor>){
    myExpand = expand
    myClasses.addAll(classes)
  }
So I want to add classes and not instances to the set.
And I want to say that it is a set of classes that extend
FoldingDescriptor
.
b
and
supertypes
won't help?
h
Hmm, I think the problem is the
is
operator. Let me read some more.
d
clazz.isInstance