Kotlin – Functions Part 3 Extension and Infix Functions

Extension Functions

In Kotlin you can extend a class and add new behavior, including the classes from Java. Kotlin supports extension functions and properties.

fun main(args: Array<String>){

    val name:String = "Kronos"
    println(name.Lol())
}

fun String.Lol() = "$this LOL"  //just add a LOL after the string

$this on the above example is the receiver object, and in this case is the String name.

It is also important that you need to have a receiver type, in this case String so you can declare an Extension function. Extension functions do not modify the classes.


Infix Functions

You declare an infix function with the help of infix keyword. Those functions can be called using the infix notation, which is the operator that you place between two operands. For example the plus (+) symbol in an addition ten + one.

fun main(args: Array<String>){

    val name:String = "Kronos"
    name.Scream("BYEEEEE!!!!!")
    name Scream ("HELLLOOOOO!!!")
}

infix fun String.Scream(text:String) = println("$this screams $text")

As you can see you can omit the dot. Also a function can be an infix function only if:

  • it is a member or an extension function
  • it has only one parameter.

Read more here.

THE END!!!

Part 1

Part 2

Part 3 this post

64190cookie-checkKotlin – Functions Part 3 Extension and Infix FunctionsKotlin – Functions Part 3 Extension and Infix Functions

Related posts

2 Thoughts to “Kotlin – Functions Part 3 Extension and Infix Functions

  1. […] Kotlin – Functions Part 3 Extension and Infix Functions […]

Comments are closed.