Friday, 2 February 2018

Kotlin: infix functions

In kotlin, you can call functions in infix notation.  Infix functions are defined using the keyword ‘infix’. Infix functions must have a single parameter.

You can make a function as infix function, if the function
a.   Is a member function (or) extension function
b.   Has only single parameter
c.   Is marked with keyword infix

Infix member function
class EvenNumber {

 infix fun isEven(num: Int): Boolean {
  if (num % 2 == 0) return true
  return false
 }

}

As you see isEven is defined as infix function using the keyword infix.

How to call isEven function?
var is5Even = obj isEven 5    // Same can be called obj.isEven(5)


InfixDemo.kt
class EvenNumber {

 infix fun isEven(num: Int): Boolean {
  if (num % 2 == 0) return true
  return false
 }

}

fun main(args: Array<String>) {
 var obj = EvenNumber()

 var is5Even = obj isEven 5    // Same can be called obj.isEven(5)
 var is6Even = obj isEven 6    // Same can be called obj.isEven(5)

 println("Is 5 even number $is5Even")
 println("Is 6 even number $is6Even")
}

Output
Is 5 even number false
Is 6 even number true


Infix extension funcitons
In kotlin, you can extend the functionality of a class, by using extension functions.


For example, below code add doubleEven function to the class EvenNumber.
infix fun EvenNumber.doubleEven(num: Int): Int {

 if (isEven(num)) {
  return num * 2
 }
 return -1
}


InfixDemo.kt
class EvenNumber {

 infix fun isEven(num: Int): Boolean {
  if (num % 2 == 0) return true
  return false
 }

}

infix fun EvenNumber.doubleEven(num: Int): Int {

 if (isEven(num)) {
  return num * 2
 }
 return -1
}

fun main(args: Array<String>) {

 var obj = EvenNumber()

 var double6 = obj doubleEven 6   // Same can be called obj.doubleEven(5)

 println("Double 6 $double6")
}


Output
Double 6 12






Previous                                                 Next                                                 Home

No comments:

Post a Comment