Generic extension functions
When we are writing utility functions, often we want them to be generic. The most common examples are extensions for collections: List
, Map
, and Set
. Here is an example of an extension property for List
:
val <T> List<T>.lastIndex: Int get() = size - 1
The preceding example defines an extension property for a generic type. This kind of extension is used for lots of different problems. As an example, starting another Activity
is a repetitive task that most often needs to be implemented in multiple places in the project. The methods provided by the Android IDE for starting an Activity
do not make it easy. Here is the code used to start a new Activity called SettingsActivity
:
startActivity(Intent (this, SettingsActivity::class.java))
Note that this simple and repetitive task needs a lot of code that is not really clear. But we can define extension functions that will make Intent
creation and Activity
without arguments much simpler using...