[英]Am I able to use the advantages of sealed classes using generics?
我想創建一個通用的“查找”方法,該方法查找提供的實體,該實體實現一個密封的類並返回它,而不必再次涉及多態性。
我想做這樣的事情,但是我還沒有找到一種滿足我想要並編譯的東西的方法。
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)
}
這個怎么樣?
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.