Sobes.tech
Middle

What happens when we use lambda expressions on older Android versions?

sobes.tech AI

Answer from AI

When lambda expressions are used in a project for older versions of Android (before API 24), the Kotlin or Java compiler (when using Java 8 lambda syntax) converts them into anonymous classes. This process is automatic and is performed using build tools such as desugaring (for Java) or bytecode generation in Kotlin.

Desugaring is a process that allows the use of new Java language features, such as lambdas, default methods in interfaces, try-with-resources, and others, on older Android versions where these features are not originally available at the JVM level (Dalvik/ART). Build tools (e.g., D8/R8) transform the bytecode generated from source code using these new language features into bytecode compatible with the target Android runtime environment.

For Kotlin, the compiler also converts lambdas into corresponding bytecode representations, often using anonymous classes. When compiling for older Android versions, this generated bytecode is also compatible with the target runtime environment.

Thus, the output is bytecode that works on older Android versions but may contain additional classes (one anonymous class per lambda), which can slightly increase the APK size and execution time (due to object creation).

// Example of a lambda in Java
Runnable r = () -> System.out.println("Hello!");
r.run();

After desugaring, this can be transformed into bytecode roughly equivalent to:

// Emulated result of desugaring for a lambda
Runnable r = new Runnable() {
    @Override
    public void run() {
        System.out.println("Hello!");
    }
};
r.run();

The process in Kotlin is similar; the compiler transforms lambdas into an equivalent form.

// Example of a lambda in Kotlin
val action = { println("Hello!") }
action.invoke()

This code will also be transformed into bytecode using anonymous classes or equivalent constructs compatible with the target Android version.

It is important to note that in modern Android development environments (Android Studio, Gradle), desugaring is enabled by default for most projects using Kotlin or certain Java versions. This makes the use of lambdas and other new language features completely transparent to the developer, without requiring additional steps to support older Android versions.