androidlistkotlinkotlin-extensionextension-function

Where to declare Kotlin extension functions in an Android app


Suppose I have the following code that I want to make as a re-usable component:

fun <T> MutableList<T>.swap(index1: Int, index2: Int) {
    val tmp = this[index1] // 'this' corresponds to the list
    this[index1] = this[index2]
    this[index2] = tmp
}

and I want to use it anywhere in my app as follows:

val l = mutableListOf(1, 2, 3)
l.swap(0, 2)

Correct me if I'm wrong but I believe that function extension declarations can exist outside of a class. So in an Android app, where would I put this declaration? Or does it even matter? Will the compile just compile the code regardless where the extension is declared and make it re-usable globally or do I have to make it part of a class?


Solution

  • You can create some file, e.g. ListExt.kt anywhere you want (for example in package main_package_name/util/ListExt.kt) and place the extension function there and it will be available in the whole project. So the content of the ListExt.kt file can be:

    package main_package_name.util
    
    fun <T> MutableList<T>.swap(index1: Int, index2: Int) {
        val tmp = this[index1] // 'this' corresponds to the list
        this[index1] = this[index2]
        this[index2] = tmp
    }
    
    // other extension functions on the Lists