Johann
Johann

Reputation: 29877

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?

Upvotes: 13

Views: 6516

Answers (4)

Sergio
Sergio

Reputation: 30725

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

Upvotes: 18

Daniel Selvan
Daniel Selvan

Reputation: 1149

For a extension to be global, you need to put it outside of class

package com.extension.globalcontext

fun <T> MutableList<T>.swap(index1: Int, index2: Int)

And to call them you need to import the package

import com.extension.globalcontext
l.swap(0, 2)

Upvotes: 4

Nelson Wright
Nelson Wright

Reputation: 506

They can be anywhere, but it seems to make sense to have extensions for a particular class in the same file and/or package. For example, extensions to String could be in StringExtensions.kt, and that could optionally be in an extensions package.

Upvotes: 4

noiaverbale
noiaverbale

Reputation: 1688

Yes, extention functions can be declared anywhere you want.

For functions of general utilities (regarding lists), I whould place them under something like /company/app/util/lists.kt.

Upvotes: 1

Related Questions