我们可以在Kotlin中使用infix通用方法吗?
编译器接受中缀+泛型方法,但是使用它的语法是什么? 例如,给定那些2个相同的方法(模随机泛型):
infix inline fun Int1.plus1(i: Int1) = Int1(this.value + i.value) infix inline fun <U> Int1.plus2(i: Int1) = Int1(this.value + i.value)
我可以写:
Int1(3).plus1(Int1(4)) Int1(3) plus1 Int1(4) Int1(3).plus2<Int>(Int1(4))
但是这个电话是无效的:
Int1(3) plus2<Int> Int1(4)
有人可以解释我为什么?
TL; DR是的,我们可以
首先,参数化这种方法没有意义
infix fun <U> Int.foo(i: Int) = ...
因为foo永远不会使用类型参数U ,所以定义了调用者和参数类型
当你参数化一个方法的时候,你可以使用类似的泛型参数从它的签名中连接一个类型
infix fun <U> U.foo (other: U) = ...
或者至少有一个
infix fun <U> Int.foo (other: U) = ... infix fun <U> U.foo (other: Int) = ...
编译器会通过参数和/或调用者对象类型来猜测U的类型
在你的情况下,编译器不能猜测U型,因为它没有连接到调用者或参数