Kotlin Infix Functions With Example

In this article, You will learn how to call infix function by using infix notation in kotlin programming language. Kotlin Infix function is declared by using keyword infix.


We can call any member function or extension function by defining them with infix modifier in kotlin object oriented programming language. But this function should have one required parameter.

In Kotlin language, There are two types in infix functions.

  1. Standard library infix function
  2. User defined infix function
 

Standard library infix functions

Standard library infix function means we do need to create new function with infix keyword. They are already created in kotlin language. There are many standard library infix functions. But here we discuss few of them.
 
or and and functions support infix notation.
 
For Example:
fun main(args: Array<string>) {
     val a = true
     val b = false

     var result1 = a or b // a.or(b)
     var result2 = a and b // a.and(b)

}

 
to() is a function that creates pair of key and value. This function also support infix notation.
 
For Example:
val map = mapOf(1 to “one”, 2 to “two”, 3 to “three”)
 
 

User Defined infix function

To create user defined function, We need to follow three rules

  1. Function is a member function or an extension function
  2. Function should have only one parameter
  3. Function is marked with infix keyword
 
class arithmetic {
     infix fun increment(n : Int): Int{
         val num = n + n
         return num
     }
}
fun main(args: Array<string>) {
     val m = arithmetic()
     val result = m increment 5
}
 
class club{
     // user defined infix member function
     infix fun getclubname(name: String):String{
     var i = when(name){
             “Cristiano Ronaldo” -> “Juventus”
             “Lional Messi” -> “Barcelona”
             “Neymar” -> “Paris Saint-Germain”
             else -> “”
         }
         return i
     }
}
fun main(args: Array<string>){
     var club = club()
     var result = club getclubname “Cristiano Ronaldo”
     println(result)
}
 
 

Leave a Reply