【问题标题】:Reference of a Java static method of a type parametrized class in KotlinKotlin 中类型参数化类的 Java 静态方法的引用
【发布时间】: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.Listprintln(toSingletonList(1, ::mutableListOf))
  • List 被选为一个众所周知的 API 用于演示目的,我在使用不适合代码示例的私有库时遇到了这个问题。

标签: java kotlin generics static-methods method-reference


【解决方案1】:

可以直接导入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))

【讨论】:

  • @lino-vote-dont-say-thanks 这是否意味着在 Kotlin 中无法创建泛型类中静态方法的合格(没有导入,带有类名前缀)方法引用?
  • @czerny 我找不到确认它的来源,但我也没有让它工作。所以我认为这(还)不可能
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多