Pat
Pat

Reputation: 13

Check if an object's class is inherited from a specific sealed class

I have a sealed class

sealed class Seal {
        object Type1
        object Type2
    }

and I would like to know an object is derived from "Seal" e.g.

when (thing) {
    is Type1 -> {}//this returns true    
    is Seal -> {}//this returns false
}

is there a way to check if "Thing" is of type "Seal" instead of checking if it's "Type1" or "Type2"?

Upvotes: 1

Views: 262

Answers (1)

Neo
Neo

Reputation: 2039

Type1 and Type2 are not of type Seal! To do so, you have to make them inherit the sealed class:

sealed class Seal {
    object Type1 : Seal()
    object Type2 : Seal()
}

And now both cases would be true:

when (thing) {
    is Type1 -> {}//this returns true    
    is Seal -> {}//this returns true    
}

More info at kolin doc.

Upvotes: 3

Related Questions