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 .
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Introduction to Kotlin Lambdas: Getting Started
25 mins
- Getting Started
- Recapping Functions
- Getting Into Lambda Expressions
- Function Types
- Lambda With Parameters
- Making Buttons Clickable
- Understanding Lambda Concepts
- Hiding the Empty UI
- Displaying Songs
- Reloading Songs
- Anonymous Functions
- Saving Songs
- Validating Song Data
- Saving Data With Validation
- Higher-Order Functions
- Understanding Closures
- Where to Go From Here?
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.
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.
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:
- Open the starter project in Android Studio 3.3 or above.
- Press Command + 1 on Mac (or Alt + 1 on Windows) to open the project structure.
- 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:
- Define a function named
showAddSongDialog
usingfun
keyword. The function takes no parameters and returns no value. - Call the
show()
function in theAddSongFragment
to show the Add Song screen.
Build the project and run on emulator or device.
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:
- 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 orUnit
. - 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. - 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:
-
lambda1
stores a lambda that takes single parameter with typeString
and returns no value. -
lambda2
proves that you can ignore the lambda parameter type as it is already specified through the variable function type. - In
lambda3
the parameter name and→
is skipped and insteadit
keyword is used.it
can be used to refer to the parameter in lambdas with only one argument. - In
lambda4
, you use the same structure aslambda3
but, in this case, you don’t make use of theString
parameter. -
lambda5
type declaration of variable represents a function with two parameters of typeInt
with return type also asInt
. In this example, you have a block code with several instructions. The last statement of lambdax + y
helps the compiler in inferring the return type of the lambda. -
lambda6
represents the simplified form oflambda5
.
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:
- Define a function
setClickListeners()
to add click listeners to buttons. - Using Kotlin extensions, you set click listener to
button_add_song_empty
. As per the documentation ofView.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 tosetOnClickListener
function, it can be moved outside the parentheses. - Set click listener to
button_add_song
button, which is displayed when the empty UI is hidden.