Home > Software engineering >  Kotlin sending an instance of sealed class as function parameter
Kotlin sending an instance of sealed class as function parameter

Time:06-10

I have a sealed class which I'd like to send instances of it to another function as an argument. The function should then compare a local instance of sealed class with its argument. How can I achieve this?

sealed class MyState {
    data class State1(val someString: String): MyState()
    object State2: MyState()
    object State3: MyState()
}

The function

fun myFunction(conditionStateClass: Class<MyState>): Boolean {
    val newState1 = MyState.State1("foo")
    val newState2 = MyState.State2
    return newState::class.java == conditionState || newState2::class.java == conditionState // Not possible
}

And I'd like to call the function

myFunction(MyState.State1::class.java)

I know this is wrong. How can I achieve a similar thing?

CodePudding user response:

You should use kotlin.reflect.KClass instead of java.lang.Class as you are writing Kotlin, and you should use isInstance to check if something is an instance of a given KClass.

fun myFunction(conditionStateClass: KClass<out MyState>): Boolean {
    val newState1 = MyState.State1("foo")
    val newState2 = MyState.State2
    return conditionStateClass.isInstance(newState1) || conditionStateClass.isInstance(newState2)
}

// Usage:
myFunction(MyState.State1::class)

Alternatively, use an inline function with a reified type parameter:

inline fun <reified T: MyState> myFunction(): Boolean {
    val newState1 = MyState.State1("foo")
    val newState2 = MyState.State2
    return newState1 is T || newState2 is T
}

// Usage:
myFunction<MyState.State1>()

Though this isn't always possible, if myFunction uses private members.

  • Related