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?
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?
You can actually test this out yourself. I personally group extensions by namespace for better organisation – Mosher