Compiler accept infix+generic methods, but what is the syntax to use it ? Example, given those 2 identical methods (modulo 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)
Someone can explain me why ?
What Is an Infix Notation? Kotlin allows some functions to be called without using the period and brackets. These are called infix methods, and their use can result in code that looks much more like a natural language.
Creating the infix function is just like creating the inline function. The only difference in syntax is that we use the infix keyword instead of inline . Now, let's see how to invoke infix functions. With the help of infix functions, we can make code more readable and concise.
Infix notation is the notation commonly used in arithmetical and logical formulae and statements. It is characterized by the placement of operators between operands—"infixed operators"—such as the plus sign in 2 + 2.
Generics are the powerful features that allow us to define classes, methods and properties which are accessible using different data types while keeping a check of the compile-time type safety. Creating parameterized classes – A generic type is a class or method that is parameterized over types.
TL;DR yes, we can
First, there's no point in parameterizing such method
infix fun <U> Int.foo(i: Int) = ...
because foo never use type parameter U, both caller and arguments types are defined
When you parameterize a method you connect a type from it's signature with generic parameter like
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) = ...
Compiler will guess type of U by argument and/or caller object types
In your case compiler can't guess U type because it's not connected neither to caller nor to argument
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With