kotlin - 通用内联函数
问题描述
假设我有一个对象可以帮助我从存储中反序列化其他对象:
val books: MutableList<Book> = deserializer.getBookList()
val persons: MutableList<Person> = deserializer.getPersonList()
方法getBookList
和getPersonList
是我编写的扩展函数。它们的逻辑几乎相同,所以我想我可以将它们组合成一种方法。我的问题是通用返回类型。这些方法如下所示:
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()
哪些不适用于泛型类型,对吗?或者这可以通过内联函数实现吗?
解决方案
您不能调用泛型类型的构造函数,因为编译器不能保证它具有构造函数(类型可能来自接口)。但是,您可以做些什么来解决这个问题,就是将“创建者”函数作为参数传递给您的函数。像这样:
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)
推荐阅读
- c# - 相对于鼠标坐标的视口内图形的真实坐标
- r - 在 ggplot 中绘制 2 个变量以显示比例/百分比,而不是总和
- android - Tolist 在 rxjava 中没有发出
- ruby-on-rails - Rails5:如何为种子参数设置变量
- angular - 如何使用返回值调用父方法Angular 2?
- android - 如何调整折叠工具栏左边距?
- git - GitHub:将错误的合并恢复为 master,但合并的文件仍然存在
- hive - 如何选择最近的记录
- webpack - 如何使 webpack-dev-server 从任何子域提供相同的服务?
- php - 错误:SQLSTATE[HY000] [1044]