Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use infix generic methods in Kotlin ?

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 ?

like image 667
Jeremy L Avatar asked Jan 22 '17 21:01

Jeremy L


People also ask

What is the use of infix in Kotlin?

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.

What's the difference between inline and infix functions?

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.

What is the use of infix?

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.

What is generic type in Kotlin?

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.


1 Answers

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

like image 181
Sergei Voitovich Avatar answered Sep 29 '22 23:09

Sergei Voitovich