首页 > 解决方案 > 通用内联函数

问题描述

假设我有一个对象可以帮助我从存储中反序列化其他对象:

val books: MutableList<Book> = deserializer.getBookList()
val persons: MutableList<Person> = deserializer.getPersonList()

方法getBookListgetPersonList是我编写的扩展函数。它们的逻辑几乎相同,所以我想我可以将它们组合成一种方法。我的问题是通用返回类型。这些方法如下所示:

fun DataInput.getBookList(): MutableList<Book> {
    val list = mutableListOf<Book>()
    val size = this.readInt()

    for(i in 0 .. size) {
        val item = Book()
        item.readExternal(this)
        list.add(item)
    }

    return list
}

是否有一些 Kotlin 魔法(可能带有内联函数)可用于检测List类型并泛化此方法?我认为问题在于val item = T()哪些不适用于泛型类型,对吗?或者这可以通过内联函数实现吗?

标签: kotlin

解决方案


您不能调用泛型类型的构造函数,因为编译器不能保证它具有构造函数(类型可能来自接口)。但是,您可以做些什么来解决这个问题,就是将“创建者”函数作为参数传递给您的函数。像这样:

fun <T> DataInput.getList(createT: () -> T): MutableList<T> {
    val list = mutableListOf<T>()
    val size = this.readInt()

    for(i in 0 .. size) {
        val item = createT()
        /* Unless readExternal is an extension on Any, this function 
         * either needs to be passed as a parameter as well,
         * or you need add an upper bound to your type parameter
         * with <T : SomeInterfaceWithReadExternal>
         */
        item.readExternal(this)
        list.add(item)
    }

    return list
}

现在您可以像这样调用该函数:

val books: MutableList<Book> = deserializer.getList(::Book)
val persons: MutableList<Person> = deserializer.getList(::Person)

推荐阅读