Bo Z
Bo Z

Reputation: 2607

Analogue of infix function from Kotlin in Java

Trying to understand deeply in infix functions. Could you please give an example of solution from Java which could be solved by infix from Kotlin. PS Please let me know if my question is incorrect if you want to devote it. It helps me asking better questions

Upvotes: 0

Views: 862

Answers (2)

Dario Seidl
Dario Seidl

Reputation: 4630

Kotlin supports operator overloading and infix functions, Java doesn't support either.

These language features are just syntactic sugar. Everything you do with operators or infix functions can be done without, but they may help greatly with the readability of your code.

An infix function is like a named operator and can be called without dot and parentheses. The example from the documentation looks like this:

    infix fun Int.shl(x: Int): Int { ... }

    // calling the function using the infix notation
    1 shl 2

    // is the same as
    1.shl(2)

Other example is for adjusting times. I like to define infix functions like

infix fun TemporalAmount.before(instant: Instant): Instant =
    instant.minus(this)

Which allows me to write

val yesterday = Period.ofDays(1) before Instant.now()

instead of

val yesterday = Instant.now().minus(Period.ofDays(1))

Upvotes: 4

Eric Martori
Eric Martori

Reputation: 2975

There is no analogous concept in Java. As explained in the official documentation It just allows you to call the function without the . and () making it cleaner and less verbose. For example:

infix fun Int.shl(x: Int): Int { ... }

// calling the function using the infix notation
1 shl 2

// is the same as
1.shl(2)

As you can see this doesn't solve anything that can't be solved by a normal function call. It is just syntax sugar.

Upvotes: 3

Related Questions