Leverage Kotlin Functions & Lambdas

May 22 2024 · Kotlin 1.9.24, Android 14, Kotlin Playground

Lesson 04: Create Trailing Lambdas

Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Now, it’s time to take your higher-order function skills to the next level. To code along, open Kotlin Playground from your browser. Let’s get going!

fun applyOperation(
    num1: Int,
    num2: Int,
    operation: (Int, Int) -> Int): Int {
  val startingTime = System.nanoTime()
  val result = operation(num1, num2)
  val endingTime = System.nanoTime()
  val elapsedTime = endingTime - startingTime
  println("Operation took $elapsedTime nanoseconds")
  return result
}
val findProductLambda = { num1: Int, num2: Int -> num1 * num2 }
fun main() {
  val numProduct = applyOperation(29, 30, findProductLambda)
  println(numProduct)
}
Operation took 45685 nanoseconds
870

Trailing Lambdas

In Kotlin, if the last parameter of a function is itself a function, the lambda can be placed outside of the parentheses where the arguments normally go. This syntax is called trailing lambdas. Now, update the applyOperation() function call to use the trailing lambda syntax:

fun main() {
  val numProduct = applyOperation(29, 30) { a, b ->
    a * b
  }
  println(numProduct)
}
fun main() {
  val numSquare= applyOperation(29, 30) { a, _ ->
    a * a
  }
  println(numSquare)
}

The it Keyword

It’s very common for a lambda expression to have only one parameter. In those scenarios, Kotlin allows you to omit the name of the parameter and use the it keyword to refer to the parameter passed to the lambda. Create a method that sends a message and then logs the message sent.

fun sendMessage(message: String, logMessage: (String) -> Unit) {
  logMessage(message)
  println("Sending message....")
}
fun main() {
  sendMessage(message = "Learning Kotlin") {
    println(it)
  }
}
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion