Infix Notation : Kotlin
Ever imagined calling a public function of a class without dot and parentheses of the parameter in Kotlin. Kotlin provides
infix notation with which we can call a function with the class object without using a dot and parentheses across the parameter. Using infix function provides more readability to a function similar to other operators like
as in Kotlin.
This post was originally posted at https://agrawalsuneet.github.io/blogs/infix-notation-kotlin/ and reposted on Medium on 7th Oct 2018.
To make a function infix notation enabled, add
infix keyword before the function.
infix fun Int.add(b : Int) : Int = this + bval x = 10.add(20)
val y = 10 add 20 // infix call
But an Infix function must satisfy the following requirements
- They must be member functions or extension functions.
- They must have a single parameter.
- The parameter must not accept a variable number of arguments and must have no default value.
What if I use an infix function with other operators.
You can but you should keep the priority of the operator in mind.