Skip to main content

Easy SDK version handling with Anko

Anko is a library for Kotlin that implements a bunch of DSLs that significantly simplifies and cleans up your Android code. One of the small pieces it offers are some extension functions to selectively execute code based on the current configuration. It looks like this:
configuration(screenSize = ScreenSize.LARGE, orientation = Orientation.LANDSCAPE) {
    // This code will be only executed
    // if the screen is large and its orientation is landscape
}
Since it was available I thought it’d be nice to use it to tidy up my code that targets different versions of the Android SDK.
configuration(fromSdk = Build.VERSION_CODES.M) {
    // This code will be only executed
    // on sdk versions 23 and later
}
However, this has a problem because I want to target multiple version ranges of the SDK. Fortunately, it turns out the function returns null if the configuration check fails. With the power of Elvis ( ?: ) the null return can distinguish when the closure hasn’t been executed and build a cascading configuration selection.
configuration(fromSdk = Build.VERSION_CODES.M) {
    // This code will be only executed
    // on sdk versions 23 and later
} ?: configuration(fromSdk = Build.VERSION_CODES.LOLLIPOP) {
    // This code will be only executed
    // on sdk versions 21 and 22
} ?: {
    // This code will only be executed on 
    // sdk version 20 and earlier
}()

Comments