Member extension functions and properties

We've seen top-level extension functions and properties, but it is also possible to define them inside a class or object. Extensions defined there are called member extensions, and they are most often used for different kinds of problem than top-level extensions.

Let's start from the simplest use case where member extensions are used. Let's suppose that we need to drop every third element of a list of String. Here is the extension function that allows us to drop every ith element:

    fun List<String>.dropOneEvery(i: Int) = 
        filterIndexed { index, _ -> index % i == (i - 1) } 

The problem with that function is that it should not be extracted as a util extension, because of the following reason:

  • It is ...

Get Android Development with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.