Anko and Extension Functions

7.3 Extension functions

An extension function is a function that adds a new behaviour to a class, even if we don’t have access to the source code of that class. It’s a way to extend classes which lack some useful functions. In Java, this is usually implemented in utility classes which include a set of static methods. The advantage of using extension functions in Kotlin is that we don’t need to pass the object as an argument. The extension function acts as part of the class, and we can implement it using this and all its public methods.

For instance, we can create a toast function that doesn’t the context as parameter, which could be used by any Context objects and those whose type extends Context , such as Activity or Service :

1 fun Context .toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) { 2 Toast.makeText( this , message, duration).show() 3 }

This function can be used inside an activity, for instance:

7 Anko and Extension Functions

1 toast( "Hello world!" ) 2 toast( "Hello world!" , Toast.LENGTH_LONG)

Of course, Anko already includes its own toast extension function, very similar to this one. The library provides functions for both CharSequence and resources, and different names for short and long toasts:

1 toast( "Hello world!" ) 2 longToast(R.string.hello_world)

Extensions can also be properties. So you can create extension properties in a very similar way. Thanks to this code below, you could add an extra property to ViewGroup to get a list of its child views:

1 val ViewGroup.childViews: List<View> 2 get () = ( 0 until childCount).map { getChildAt(it) }

Don’t pay much attention to the implementation yet, as we haven’t covered some of the concepts there.

Extension functions don’t really modify the original class, but the function is added as a static import where it is used. Extension functions can be declared in any file, so a common practice is to create files which include a set of related functions.

And this is the magic behind many Anko features. From now on, you can create your own magic too.

This chapter has little changes. Anyway, the source can be found here¹⁸ .

¹⁸ https://github.com/antoniolg/Kotlin-for-Android-Developers/tree/chapter-7