Kotlin’s Extension functions, Higher order functions and Lambdas with receivers

Roselyne Makena
2 min readJul 12, 2019

--

Extension functions
To quickly add a new extension functionality — i.e allow it to be invoked directly on the object, all you need to do in kotlin is add a prefix of the class to the new method and using the this keyword to refer to that instance of the object, this eliminates the need to pass in a parameter.

Example:
- Let’s add a functionality that adds dashes before and after a string.


fun main(args: Array<String>) {
println ("hooray".processString())
println
(processString("hooray"))

}
//Add an extension function(no param needed)
fun String.processString(): String {
return "-${this}-"
}
//Add a method to process the String(pass in a String param)
fun processString(string: String): String {
return "-${string}-"
}

Higher Order functions

  • In the most basic definition — a higher order function is a function that -
    a) takes in a function as an parameter
    b) returns a function

Example:

fun main(args: Array<String>) {

val ageIn50years : (Int, String) -> String = {name, age -> "$name will be $age years in 50years time"}
setInfo("Joy", ageIn50years)
}

fun setInfo(name: String, ageCalculator: (Int, String) -> String ) {
val result = ageCalculator(25, "Joy")
print(result)
}

In the above example, we have a function setInfo that takes in a name parameter and a function parameter. The fact that it takes it a function, makes it a higher order function.

Lambdas with Receivers.
- These are also referred to as `functional literal with receiver` — They are basically extension functions — which can be stored and passed around as properties.
The most basic example of lambda with receiver is Kotlin’s apply().

Example: — kotlin’s apply() — where the receiver — an instance of T is returned.

public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }

Thanks for reading!

--

--

Roselyne Makena
Roselyne Makena

Written by Roselyne Makena

Design thinking analytic. Born creative with design edge. Software QA Engineer. I write articles at: senseitechtips.com

No responses yet