英文:
Reference of a Java static method of a type parametrized class in Kotlin
问题
如何在Kotlin中为泛型类的Java静态方法编写方法引用?
下面的示例显示,::
操作符仅适用于非泛型类(在此示例中为Collections
)。然而,使用相同的方法似乎不适用于具有类型参数的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)) // 编译错误:接口List<E : Any!>需要一个类型参数
println(toSingletonList(1, List<Int>::of)) // 编译错误:未解析的引用:of
}
英文:
How to write method reference to a Java static method of a generic class in Kotlin?
Example below shows that ::
operator works only in case of non-generic classes (Colections
in this case). However using the same approach doesn't seem to work for List
interface that has a type parameter.
<!-- language: lang-kotlin -->
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
}
答案1
得分: 3
You can import the of()
method directly:
import java.util.List.of
And then you're able to reference it directly:
println(toSingletonList(1, ::of))
If you happen to run into conflicts. E.g. by importing also Set.of
you may use import aliasing:
import java.util.List.of as jListOf
import java.util.Set.of as jSetOf
and then use that alias as a method reference
println(toSingletonList(1, ::jListOf))
println(toSingletonSet(1, ::jSetOf))
英文:
You can import the of()
method directly:
import java.util.List.of
And then you're able to reference it directly:
println(toSingletonList(1, ::of))
If you happen to run into conflicts. E.g. by importing also Set.of
you may use import aliasing:
import java.util.List.of as jListOf
import java.util.Set.of as jSetOf
and then use that alias as a method reference
println(toSingletonList(1, ::jListOf))
println(toSingletonSet(1, ::jSetOf))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论