我们可以在Kotlin中使用中缀泛型方法吗?

Jer*_*y L 6 generics infix-notation kotlin

编译器接受中缀+泛型方法,但使用它的语法是什么?例如,给出了两个相同的方法(模任意通用类型):

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)
Run Code Online (Sandbox Code Playgroud)

我可以写:

Int1(3).plus1(Int1(4))
Int1(3) plus1 Int1(4)
Int1(3).plus2<Int>(Int1(4))
Run Code Online (Sandbox Code Playgroud)

但这个电话无效:

Int1(3) plus2<Int> Int1(4)
Run Code Online (Sandbox Code Playgroud)

有人能解释我为什么吗?

Ser*_*ich 5

TL;DR 是的,我们可以

首先,参数化这样的方法没有意义

infix fun <U> Int.foo(i: Int) = ...
Run Code Online (Sandbox Code Playgroud)

因为foo从不使用类型参数U,所以调用者和参数类型都被定义

当您参数化方法时,您可以将类型从其签名与通用参数连接起来,例如

infix fun <U> U.foo (other: U) = ...
Run Code Online (Sandbox Code Playgroud)

或至少其中之一

infix fun <U> Int.foo (other: U) = ...
infix fun <U> U.foo (other: Int) = ...
Run Code Online (Sandbox Code Playgroud)

编译器将通过参数和/或调用者对象类型猜测U的类型

在您的情况下,编译器无法猜测U类型,因为它既没有连接到调用者也没有连接到参数