【发布时间】:2019-10-25 17:28:20
【问题描述】:
以下示例在 Kotlin 1.3.21 中完全合法:
fun <T> foo(bar: T): T = bar
val t: Int = foo(1) // No need to declare foo<Int>(1) explicitly
但为什么类型推断不适用于高阶函数?
fun <T> foo() = fun(bar: T): T = bar
val t: Int = foo()(1) // Compile error: Type inference failed...
当使用高阶函数时,Kotlin 强制调用站点为:
val t = foo<Int>()(1)
即使明确指定foo的返回类型,类型推断仍然失败:
fun <T> foo(): (T) -> T = fun(bar: T): T = bar
val t: Int = foo()(1) // Compile error: Type inference failed...
但是,当泛型类型参数与外部函数共享时,它可以工作!
fun <T> foo(baz: T) = fun (bar: T): T = bar
val t: Int = foo(1)(1) // Horray! But I want to write foo()(1) instead...
如何编写函数foo 以便foo()(1) 能够编译,而bar 是泛型类型?
【问题讨论】:
标签: kotlin