Sitemap
iamVariable

iamVariable

Experienced Mobile Application Developer skilled in the full software development lifecycle, including analysis, design, development, and deployment.

Kotlin Higher-order functions

2 min readJul 24, 2024
Press enter or click to view image in full size

Use of let, run, with, also, apply — These are higher-order functions in Kotlin that provides a concise way to perform operations on objects.

Each function has a specific use case and can be handy in different scenarios. For example, let is used for null-safe operations, run is used for scoping functions, with is used for operating on an object without the need to call its methods explicitly, also is used for performing additional actions on an object, and apply is used for initializing an object.

Get iamVariable’s stories in your inbox

Join Medium for free to get updates from this writer.

Lets see some example to understand.

  1. let: The let function is used for null-safe operations. It is often used with the safe call operator ?.. The letfunction is called on an object and it returns the result of the lambda expression.
val listWithNulls: List<String?> = listOf("Kotlin", null)
for (item in listWithNulls) {
item?.let { println(it) } // prints Kotlin and ignores null
}

2. run: The run function is used for scoping functions. It creates a temporary scope where you can run complex operations on an object. The last expression in the run block is the result of the entire block.

val length = run {
val str = "run function"
str.length // returns length of str
}
println("Length of the string is $length")

3. with: The with function is used for operating on an object without the need to call its methods explicitly. It is called with an object and a lambda expression.

data class Person(var name: String, var age: Int, var city: String)
val john = Person("John", 25, "New York")
with(john) {
println("Name is $name, age is $age, and city is $city")
}

4. also: The also function is used for performing additional actions on an object. It is called on an object and it returns the object itself.

val numbers = mutableListOf("one", "two", "three")
numbers.also { println("The list elements before adding new one: $it") }.add("four")

5. apply: The apply function is used for initializing an object. It is called on an object and it returns the object itself.

data class Person(var name: String, var age: Int, var city: String)
val person = Person("John", 25, "New York").apply {
age = 30
city = "San Francisco"
}
println(person)

I hope now you got some clear idea about these higher order functions.

Happie coding:)

--

--

iamVariable
iamVariable

Written by iamVariable

Experienced Mobile Application Developer skilled in the full software development lifecycle, including analysis, design, development, and deployment.