通用Kotlin工厂的未经检查的演员表

时间:2019-03-07 22:13:58

标签: android generics kotlin

我正试图在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中实现这种行为?

1 个答案:

答案 0 :(得分: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>("")

希望这可以为您提供帮助。