Introduction to Kotlin Lambdas: Getting Started

In this tutorial you will learn how to use lambda expressions and other functional literals provided by Kotlin for the Android platform. Lambda expression is simplified representation of a function. It can be passed as a parameter, stored in a variable or even returned as a value. By Rachit .

Leave a rating/review
Download materials
Save for later
Share

In this tutorial, you will learn how to use lambda expressions and other functional literals provided by Kotlin for the Android platform.

Lambda expression is a simplified representation of a function. It can be passed as a parameter, stored in a variable or even returned as a value.

Note: If you are new to Android app development or just getting started, you should get a head start from Kotlin for Android: An Introduction.

To practice using lambda expressions, you will build a simple app to save and manage your favorite songs. It will have the functionality to:

  • Add songs to a Favorite list.
  • Display favorite songs on a list with playlist range.

Cassette Starter UI

While doing so, you will explore the following Kotlin topics:

  • Lambdas
  • Anonymous functions
  • Higher-order functions
  • Closures

Time to start learning!

Getting Started

Use the Download Materials button at top or bottom of this tutorial to download the starter project.

Once the project is downloaded:

  1. Open the starter project in Android Studio 3.3 or above.
  2. Press Command + 1 on Mac (or Alt + 1 on Windows) to open the project structure.
  3. Open the java and res folders.

Take a moment to review the main project files to know more about their usage.

  • MainActivity.kt: Shows all the songs added by you on the UI. Initially, it shows an empty screen as there is no data.
  • AddSongFragment.kt: Shows the UI to enter and save song details.
  • SongStore.kt: Helper class to manage and store songs in Preferences.
  • activity_main.xml: Layout file for song list UI.
  • dialog_add_song.xml: Layout file for new song addition UI.

Press Control + R (or Shift + F10 on Windows) to run the app on an emulator or device.

Recapping Functions

A function is a group of statements written to perform a specific task. It can have any number of parameters as input, and it can return one or more values.

Open the MainActivity.kt file and add the following code below the onCreate() function:

// 1
private fun showAddSongDialog() {
  // 2
  AddSongFragment.show(supportFragmentManager)
}

Here, you:

  1. Define a function named showAddSongDialog using fun keyword. The function takes no parameters and returns no value.
  2. Call the show() function in the AddSongFragment to show the Add Song screen.

Build the project and run on emulator or device.

Cassette Starter UI

Click Add Song button. Nothing happens. This is because you must still set the listeners on the buttons.

Next, you will add lambda expressions to the app. You will use them to set click listeners and also add a bit of text style to your song list.

Getting Into Lambda Expressions

A lambda expression is a shorter way of describing a function. It doesn’t need a name or a return statement. You can store lambda expressions in a variable and execute them as regular functions. They can also be passed as parameters to other functions or be the return value.

You define lambda expressions following this syntax:

  val lambdaName : Type = { parameterList -> codeBody }

Function Types

Function types are notation similar to a function signature. A function type has a parameter list inside parentheses and a return type. For example, (A, B) -> C represents a function that takes two parameters of type A and B and returns a value of type C. You can also specify empty parameter lists and no return value with Unit.

Example:

  // 1
  val lambda1: () -> Unit = { println("Hello, world") }
  // 2
  val lambda2 = { println("Hello, world") }
  // 3
  lambda2()

In the example code above, you:

  1. Assign the lambda expression to a variable lambda1. It has a function type of () -> Unit. The type represents a function that takes no parameters and returns no value or Unit.
  2. Assign another lambda expression to another variable lambda2. You can find that variable type can be ignored for simple lambda expressions thanks to Kotlin Type Inference.
  3. Execute the lambda expression in a similar way as function calls.

Lambda With Parameters

A lambda expression can have one or more parameters. You specify the parameters before the symbol followed by codeBody. The compiler interprets the return type of lambda by the last executable statement in its body:

You specify lambda expressions in following formats:

  // 1 
  val lambda1: (String) -> Unit = { name: String -> println("Hello, $name") }
  // 2 
  val lambda2: (String) -> Unit = { name -> println("Hello, $name") }
  // 3 
  val lambda3: (String) -> Unit = { println("Hello, $it") }
  // 4
  val lambda4: (String) -> Unit = { println("Hello, World!") }
  // 5
  val lambda5: (Int, Int) -> Int = {  x, y -> 
    print(x)
    print(y)
    x + y
  }
  // 6
  val lambda6 = {x: Int, y: Int -> x + y }

In the examples above, you learn:

  1. lambda1 stores a lambda that takes single parameter with type String and returns no value.
  2. lambda2 proves that you can ignore the lambda parameter type as it is already specified through the variable function type.
  3. In lambda3 the parameter name and is skipped and instead it keyword is used. it can be used to refer to the parameter in lambdas with only one argument.
  4. In lambda4, you use the same structure as lambda3 but, in this case, you don’t make use of the String parameter.
  5. lambda5 type declaration of variable represents a function with two parameters of type Int with return type also as Int. In this example, you have a block code with several instructions. The last statement of lambda x + y helps the compiler in inferring the return type of the lambda.
  6. lambda6 represents the simplified form of lambda5.

Next, you will explore the lambda expression use cases in the app.

Making Buttons Clickable

Open MainActivity.kt. It shows an empty UI with a Add Song button. Add the following function below the showAddSongDialog():

// 1
private fun setClickListeners() {
  // 2
  button_add_song_empty.setOnClickListener {
    showAddSongDialog()
  } 
  // 3
  button_add_song.setOnClickListener {
    showAddSongDialog()
  }
}

After adding the above code, press Opt + Enter (or Alt + Enter on Windows) to import the button_add_song_empty and button_add_song references if Android Studio doesn’t do it automatically.

In this code, you:

  1. Define a function setClickListeners() to add click listeners to buttons.
  2. Using Kotlin extensions, you set click listener to button_add_song_empty. As per the documentation of View.OnClickListener interface, it provides a single function to implement. You can replace such interface implementations with lambdas. Also, as the lambda is only and last parameter to setOnClickListener function, it can be moved outside the parentheses.
  3. Set click listener to button_add_song button, which is displayed when the empty UI is hidden.