Middle+
What is desugaring and how does this process affect Android development?
sobes.tech AI
Answer from AI
Desugaring is the process of transforming Java syntax "sugar" (such as lambda expressions, method references, default methods in interfaces) into bytecode compatible with older Android SDK versions, where these features were not originally supported.
This is achieved through code transformation at compile time or during the Android Gradle Plugin build.
Impact on development:
- Access to modern language features: Allows the use of new Java features (e.g., Stream API,
java.time) even on older Android versions, increasing productivity and code readability. - Compatibility: Ensures code using new Java features works across a wide range of devices with different OS versions.
- APK size: In some cases, it may increase APK size due to additional bytecode and auxiliary classes for emulating new features.
- Performance: May have a slight impact on performance compared to native support of the same functionality in newer Android versions.
- Build complexity: Desugaring integration is automatic via AGP, simplifying setup for developers. Ensure that the used AGP and Java versions are compatible.
Example of lambda expression usage requiring desugaring for support on older APIs:
// Example of lambda expression usage
List<String> list = Arrays.asList("apple", "banana", "cherry");
list.forEach(s -> System.out.println(s));
// Desugaring transforms this roughly into the following (implementation may vary):
/*
List<String> list = Arrays.asList("apple", "banana", "cherry");
for (String s : list) {
// invoke appropriate method reference or synthetic class
System.out.println(s);
}
*/
Desugaring for API interfaces (e.g., java.time) is done via a special library and configurations in build.gradle.
// build.gradle (Module level)
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
// This option enables desugaring for Java 8+ syntax
// and allows using APIs from android.jar for older Android versions
// which were added later (e.g., java.time)
// Requires minSdk >= 21
coreLibraryDesugaringEnabled true
}
}
dependencies {
// This dependency provides implementation of missing APIs
// required for coreLibraryDesugaringEnabled
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}