Search code examples
infix-notation

How to use infix notation in Android properly (Kotlin language)?


I have read Kotlin docs as well as the wikipedia links (https://en.wikipedia.org/wiki/Infix_notation#:~:text=Infix%20notation%20is%20the%20notation,plus%20sign%20in%202%20%2B%202), but unfortunately I am still unable to make use of this notation in my code.

Could someone please let me know, how can I use it?


Solution

  • Before jumping on to the code, let’s look at the rules of it’s usage (From the docs: https://kotlinlang.org/docs/functions.html#infix-notation):

    1. Infix notation must be used with member functions or extension functions
    2. They must have a single parameter
    3. The parameter must not accept variable number of arguments and must have no default value.

    Keeping these pointers in mind, you can achieve the following:

    fun Int.add(x: Int) = this.plus(x) //This is a simple Extension function without infix notation
    
    infix fun Int.subtract(x: Int) = this.minus(x) //Added infix notation here
    
    fun main() {
        val sum = 10.add(20)
        println(sum) //prints 30
    
        val sub = 100 subtract 30 //Notice that there is no dot(.) and parenthesis
        println(sub) //prints 70
    }
    

    This is how we can use infix notations and get rid of the dots(.) and parenthesis and they will work the same. This increases code readability.