Kotlin for Java and Android Developers — Part 2

Lambdas

Lambda is the block of code which can be used as an object or we can say Lambda is a type of object which holds a block of code. Comparing it to java we can say a lambda is similar to an anonymous object with only one method.

// Java implementation
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/* actions on click */
}
});
// Kotlin implementation
button.addActionListener { /* actions on click */ }
val sum = { x: Int, y: Int -> x + y }
println(sum(1, 2))
fun sum(x: Int, y: Int) = x+y
var sum = { x: Int, y: Int -> x + y }
sum = { y: Int -> y + 10 }
val sum = { x: Int -> x + 5 }
val sum = { it + 5 }
val calculated : (Int,Int) -> Int
//This won't compile
calculated = { x double, y double -> x+y }
val calculated : (Int,Int) -> Unit = { x, y -> print(x+y) }
fun convert (value: Double ,formulae: (Double) -> Double) : Double {
var result = formulae(value)
return result
}
convert(30.0, { v: Double -> v * 1.8 + 32 })

Nullable types

In java we often get NullPointerException in our code. We have to take care of our object to be null. In kotlin you will hardly ever get NullPointerException.

var str : String? = "SomeValue"
// str can be assigned null value
str = null
var car : Car? = Car()
// in kotlin
car?.drive()
// in java
if(car != null){
car.drive()
}
// in java 
if(car != null) {
System.out.prinlt(car.modelName);
}
// in kotlin with let
car?.let {
println(car.modelName)
}
// to kotlin compiler this is unsafe code
if(car != null){
println(car.modelName)
} else {
println("Unknown")
}
// kotlin code
car?.modelName ?: "Unknown"

Conclusion

Lambdas are very important part of functional programming. In case of non functional programming, it accepts data input and provides a data output. Functional programs can read functions as input and can generate functions as output. Object oriented programs combine data with their functions, but in functional programming we combine functions with functions. That is why understanding of Lambda functions are so important in kotlin.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store