Home » Blog » Infix Functions

Infix Functions

Member functions and extensions with a single parameter can be turned into infix functions.

  • Defines an infix extension function on Int.
  • Calls the infix function.
  • Creates a Pair by calling the infix function to from the standard library.
  • Here’s your own implementation of to creatively called onto.
  • Infix notation also works on members functions (methods).
  • The containing class becomes the first parameter.

Note that the example uses local functions (functions nested within another function).

fun main() {

  infix fun Int.times(str: String) = str.repeat(this)        
  println(2 times "Bye ")                                    

  val pair = "Ferrari" to "Katrina"                          
  println(pair)

  infix fun String.onto(other: String) = Pair(this, other)   
  val myPair = "McLaren" onto "Lucas"
  println(myPair)

  val sophia = Person("Sophia")
  val claudia = Person("Claudia")
  sophia likes claudia                                       
}

class Person(val name: String) 
{
  val likedPeople = mutableListOf<Person>()
  infix fun likes(other: Person) { likedPeople.add(other) }  
}

 

Leave a Reply

Your email address will not be published.