Kotlin Bricks: Extension functions to clean up Compat classes

You have to hand it to Google and the Android team for solving the difficult problem of OS distribution and the long tail of support we must provide as Android developers. One solution is classes like ViewCompat, TextUtilsCompat, and ActivityCompat.

These days it seems like there is a Compat version of every class. It often leads to some ugly and verbose syntax or worse, you end up using the same old deprecated version. Resources and ResourcesCompat bugs me every time and it really mucks up otherwise readable code. Here are a few snippets I use to hide away the mess.

fun Resources.color(@ColorRes color: Int, theme: Resources.Theme? = null): Int {
    return ResourcesCompat.getColor(this, color, theme)
}

fun Resources.colorStateList(@ColorRes color: Int, theme: Resources.Theme? = null): ColorStateList {
    return ResourcesCompat.getColorStateList(this, color, theme)!!
}

fun Resources.drawable(@DrawableRes drawable: Int, theme: Resources.Theme? = null): Drawable {
    return ResourcesCompat.getDrawable(this, drawable, theme)!!
}

Using extension functions we can make the plain old Resources from your Fragment or View use the Compat variant. The solution can not only provide a sensible default, but also allows you to customize the theme if you want to. When you go to use this, you'll see how much cleaner it is.

// from support library
ResourcesCompat.getColor(resources, R.color.red, null)

// much better with extention function
resources.color(R.color.red)