简体   繁体   中英

Am I able to use the advantages of sealed classes using generics?

I want to create a generic "find" method, that finds a provided entity that implements a sealed class and returns it without having to recur to polymorphism.

I wanted to do something like this, but I have not found a way that satisfies everything I want and compiles.

sealed class Spell(val id: Long)
class Fireball(id: Long, val name: String): Spell(id)
class Storm(id: Long, val size: String): Spell(id)

inline fun <reified T: Spell> find(id: Long): T =
    when (T) {
        Fireball -> Fireball(id, "fireball")
        Storm -> Storm(id, "3 acres")
    }

fun main() {
    find<Fireball>(3)
}

How about this?

inline fun <reified T : Spell> find(id: Long): T =
    when (T::class) {
        Fireball::class -> Fireball(id, "fireball")
        Storm::class -> Storm(id, "3 acres")
        else -> throw IllegalStateException()
    } as T

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM