简体   繁体   English

我可以使用泛型使用密封类的优点吗?

[英]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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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