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 in
, is
, 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.
Please continue reading at https://agrawalsuneet.github.io/blogs/infix-notation-kotlin/
It's completely free. No Account signup. No membership required. No Gimmick.
And we are done. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.
Reference: Kotlin docs