未经检查的铸造在通用kotlin工厂

问题描述 投票:1回答:1

我正在尝试在kotlin中创建一个通用工厂,用于将一些字符串解析为Model类:

internal interface Model

data class UserId(val id: String, val name: String, val link: String): Model
data class Shelf(val id: String, val name: String, val bookCount: Int): Model

internal inline fun <reified T: Model> getParser(): Parser<T> {
    return when (T::class) {
            UserId::class -> UserIdParser() as Parser<T>
            Shelf::class -> UserShelvesParser() as Parser<T>
            else -> throw Exception("can't match proper parser")
        }
}

internal interface Parser<out T: Model> {
    fun parse(xml: String): T
}


internal class UserIdParser : Parser<UserId> {
    override fun parse(xml: String): UserId {
        return parseUserId(xml)
    }
}

internal class UserShelvesParser : Parser<Shelf> {
    override fun parse(xml: String): Shelf {
        return parseShelf(xml)
    }
}
// for example
internal fun parseUserId(xml: String) = UserId("123", "owl", "ya.ru")
internal fun parseShelf(xml: String) = Shelf("123", "to-read", 20)

所以在客户端代码中,我可以这样写:

val t = getParser<UserId>().parse("")

它有效,但在getParser方法我有警告Unchecked cast from UserIdParser to Parser<T>。如果没有惯用的警告,我怎么能在kotlin中实现这样的行为呢?

android generics kotlin
1个回答
3
投票

这与您的目标略有不同,但它没有任何警告:

internal interface Model

data class UserId(val id: String, val name: String, val link: String) : Model
data class Shelf(val id: String, val name: String, val bookCount: Int) : Model

internal inline fun <reified T : Model> parse(xml: String) = when (T::class) {
    UserId::class -> parseUserId(xml)
    Shelf::class -> parseShelf(xml)
    else -> throw Exception("can't match proper parser")
} as T

// for example
internal fun parseUserId(xml: String) = UserId("123", "owl", "ya.ru")

internal fun parseShelf(xml: String) = Shelf("123", "to-read", 20)

然后就可以这样调用它:

val t = parse<UserId>("")

希望这可以帮到你。

热门问题
推荐问题
最新问题