首页 > 解决方案 > Kotlin 无法通过方法引用推断 Function 的类型

问题描述

为什么在下面的示例中,使用mapTwoKotlin 无法推断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
}

标签: genericskotlintypes

解决方案


类型推断不是编译错误的原因。mapTwo<List<Int>>(::mapper)由于具有不可分配给::mapper的类型(T) -> List<T>( ),因此也不会编译。KFunction1<T, List<T>>Function<Int, U>


推荐阅读