【发布时间】:2020-11-19 12:33:46
【问题描述】:
如何在 Kotlin 中编写对泛型类的 Java 静态方法的方法引用?
下面的示例显示:: 运算符仅适用于非泛型类(在这种情况下为Colections)。但是,使用相同的方法似乎不适用于具有类型参数的 List 接口。
import java.util.Collections
import java.util.List
fun toSingletonList(item: Int, toList: (Int) -> MutableList<Int>): MutableList<Int> {
return toList(item)
}
fun main() {
println(toSingletonList(1, { Collections.singletonList(it) }))
println(toSingletonList(1, Collections::singletonList))
println(toSingletonList(1, { List.of(it) }))
println(toSingletonList(1, List::of)) // not compilable: One type argument expected for interface List<E : Any!>
println(toSingletonList(1, List<Int>::of)) // not compilable: Unresolved reference: of
}
【问题讨论】:
-
不要在 Kotlin 中使用
java.util.List,println(toSingletonList(1, ::mutableListOf)) -
List被选为一个众所周知的 API 用于演示目的,我在使用不适合代码示例的私有库时遇到了这个问题。
标签: java kotlin generics static-methods method-reference