Greatness of Kotlin : Android API compatibility

A great thing about Kotlin is how its developers have taken into account the nicest features of other languages and added them to Kotlin. One of these nice features is extension functions which allows us to share code very easily between different parts of our programs.


Sometimes, the Android Support Library provides compatibility helpers (like ViewCompat or ContextCompat) but for few methods, you need to handle the different cases on your own.

The Java way

If you have ever worked with Java, you probably used the following pattern to handle Android API compatibility:

public class DragCompat {
    public static void startDragAndDrop(View view, ClipData data) {
View.DragShadowBuilder dragShadowBuilder = new View.DragShadowBuilder(view);
if (Build.VERSION.SDK_INT >= 24)
view.startDragAndDrop(data, dragShadowBuilder, null, 0);
view.startDrag(data, dragShadowBuilder, null, 0);

Then you would have to call DragCompat.startDragAndDrop(view, clipData) to start your drag and drop.

The Kotlin way

In Kotlin, we could make this code look a bit better. In a new file (i.e. DragCompat.kt), we could define a top-level function as follows:

fun View.startDragAndDropCompat(data: ClipData) {
val dragShadowBuilder = View.DragShadowBuilder(this)
if (Build.VERSION.SDK_INT >= 24)
startDragAndDrop(data, dragShadowBuilder, null, 0)
startDrag(data, dragShadowBuilder, null, 0)

And finally, you can call this brand new method on any android view instance: myView.startDragAndDropCompat(clipData) .


It does not change a lot the way you call the method, but it allows you to not look for helper methods. The functions you create look like they are directly in the base class (thanks to auto-completion). Moreover, when typing view.startDrag , auto-completion will directly show you 3 methods: the deprecated startDrag(...) , the one you should use for new APIsstartDragAndDrop(...) and finally the one you defined yourself startDragAndDropCompat(...).