In this demo, you’ll create a lambda function and learn how to call it. To code along, open Kotlin Playground from your browser. Let’s get going.
First, you’ll create a lambda expression that takes one parameter of type String. Inside the expression, check the length of the string passed. If the length is greater than 15, print “A very long string” on the screen. Otherwise, print the value of the string passed to the expression.
val stringLambda = { myString: String ->
val stringLength = myString.length
if (stringLength > 15) {
println("A very long string")
} else {
println(myString)
}
}
Next, call the lambda expression from the main() function and pass a String argument.
fun main() {
stringLambda("A quick brown fox jumped over a lazy dog!")
}
When you run the code, “A very long string” is printed on the screen.
Instead of printing the message, you’d like to return the string’s length multiplied by 100. Update the lambda expression to return a value:
val stringLambda = { myString: String ->
val stringLength = myString.length
stringLength * 100
}
The last expression is the value that will be returned when the lambda is executed: in this case, the length of the string multiplied by 100.
In the main() function, assign the value returned by the stringLambda expression to the newLength variable and print the value stored in that newLength variable.
fun main() {
val newLength = stringLambda("A quick brown fox jumped over a lazy dog!")
println(newLength)
}
When you run the code, “4100” is printed on the screen.
As you saw in the previous section, Kotlin can infer the type of the lambda expression. Sometimes, the compiler cannot infer the type. In such cases, you have to explicitly define the type of your lambda.
For example, say you want to create a lambda that takes two numbers, finds their sum, and returns the sum as a string. You can write an expression like this:
val stringSum: (Int, Int) -> String = { num1: Int, num2: Int ->
val sum = (num1 + num2)
sum.toString()
}
The lambda takes two arguments of type Int, and its return type is of type String.
Then, you call the lambda function from the main() function like this:
fun main() {
val result = stringSum(100, 30000)
println("$result")
}
When you run the code, it prints “30100” on the screen.
That ends the demo. Now, continue to the lesson summary.