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 not prepared for different types of list (such as a list of
User
orInt
) - It is a rarely used function, so it probably won't be used anywhere else in the project
This is why we would want to keep it private, and it is a good idea to keep it...