如何在 Kotlin 中编写对泛型类的 Java 静态方法的方法引用?
下面的示例显示 ::
运算符仅适用于非泛型类(本例中为 Collections
)。然而,使用相同的方法似乎不适用于具有类型参数的 List
接口(interface)。
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
}
最佳答案
您可以直接导入of()
方法:
import java.util.List.of
然后您就可以直接引用它:
println(toSingletonList(1, ::of))
如果您碰巧遇到冲突。例如。通过还导入 Set.of
您可以使用导入别名:
import java.util.List.of as jListOf
import java.util.Set.of as jSetOf
然后使用那个别名作为方法引用
println(toSingletonList(1, ::jListOf))
println(toSingletonSet(1, ::jSetOf))
关于java - Kotlin 中类型参数化类的 Java 静态方法的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63161729/