Advertisements
When I attempt to use Optional.empty()
, my IDE warns me that Call requires API level 24 (current min is 21): java.util.Optional#empty
.
I’m assuming I cannot use Optional. Should I use null
? Is there a best-practice alternative?
>Solution :
You can use Java’s Optional, even with an older min SDK level. The key is to add this to your ‘build.gradle’:
android {
compileOptions {
// Flag to enable support for the new language APIs
coreLibraryDesugaringEnabled true
// Sets Java compatibility to Java 8
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
// Use version 1.1.5 if you have Gradle older than 7.3.0
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.2.2'
}
This will instruct Grade to compile your Java 8 code using Optionals, even lambdas and more to Java 7 bytecode using some tricks. Note that you need Gradle version 4.0.0 or later for thos to work. You can find more information on what other features you can use by doing this on the official Android Developer website, but most notable are:
- lambdas
- Streams
- newer collections