【问题标题】:Kotlin cannot infer type of Function with method referenceKotlin 无法通过方法引用推断 Function 的类型
【发布时间】:2019-10-29 23:21:42
【问题描述】:

为什么在下面的示例中,mapTwo Kotlin 无法推断出a 的类型?

fun <U> mapOne(f: (Int) -> U): U = TODO()
fun <U> mapTwo(f: Function<Int, U>): U = TODO()

fun <T> mapper(a: T): List<T> = TODO()

fun main() {
    mapOne(::mapper)
    mapTwo(::mapper) //won 't compile
}

【问题讨论】:

    标签: generics kotlin types


    【解决方案1】:

    类型推断不是编译错误的原因。 mapTwo&lt;List&lt;Int&gt;&gt;(::mapper) 也不会编译,因为 ::mapper 的类型为 (T) -&gt; List&lt;T&gt; (KFunction1&lt;T, List&lt;T&gt;&gt;),不能分配给 Function&lt;Int, U&gt;

    【讨论】:

      猜你喜欢
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 2011-04-07
      • 2021-04-06
      • 1970-01-01
      相关资源
      最近更新 更多