Java中泛型类的静态方法的引用在Kotlin中的写法。

huangapple go评论88阅读模式
英文:

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) -&gt; MutableList&lt;Int&gt;): MutableList&lt;Int&gt; {
    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&lt;E : Any!&gt;
    println(toSingletonList(1, List&lt;Int&gt;::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))

huangapple
  • 本文由 发表于 2020年7月30日 04:11:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63161729.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定