How to place a Kotlin extension in a class file?

710 views Asked by At

Maybe this question is answered in the official doc, but I'm not seeing it...

In Swift we are used to write something like

class Jazz {
...
}

extension Jazz {
    func swing() {
    ...
    }
}

and place that whole code snippet in a single file, say Jazz.swift.

We don't seem to be able to do the corresponding thing in Kotlin? I'm always finding my selfe writing e.g. one Jazz.kt and one JazzExtensions.kt, which simply isn't always the clearest way of structuring the code.

Any input on this is appreciated.

2

There are 2 answers

1
guenhter On BEST ANSWER

You can place the extension function inside or outside the class:

Outside:

class Jazz { ... }

fun Jazz.bar() {
    println("hello")
}

Inside (in the companion object):

import YOUR_PACKAGE.Jazz.Companion.bar

fun main(args: Array<String>) {
    Jazz().bar()
}

class Jazz {
    companion object {
        fun Jazz.bar() {
            println("hello")
        }
    }
}
2
Alex Romanov On

It's not very different from Swift:

class Jazz {
    val a = "Jazz"
}

fun Jazz.swing() = a

////////////

fun main(args: Array<String>) {
    print(Jazz().swing()) // >>> Jazz
}