Can we use common infix methods in Kotlin?

The compiler accepts infix + generic methods, but what is the syntax for using it? An example, given those two identical methods (modulo an arbitrary generic type):

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) 

I can write:

 Int1(3).plus1(Int1(4)) Int1(3) plus1 Int1(4) Int1(3).plus2<Int>(Int1(4)) 

but this call is invalid:

 Int1(3) plus2<Int> Int1(4) 

Can anyone explain to me why?

+6
source share
1 answer

TL DR yes we can

Firstly, there is no point in parameterizing such a method

 infix fun <U> Int.foo(i: Int) = ... 

since foo never uses a parameter of type U , the types of callers and arguments are defined

When parameterizing a method, you connect the signature type to it with a common parameter, for example

 infix fun <U> U.foo (other: U) = ... 

or at least one of them

 infix fun <U> Int.foo (other: U) = ... infix fun <U> U.foo (other: Int) = ... 

The compiler guesses type U by arguments and / or object types of the calling object

In your case, the compiler cannot guess the type of U , because it is not connected to either the caller or the argument

+4
source

Source: https://habr.com/ru/post/1014306/


All Articles