Search code examples
kotlinkotlin-extension

How to place a Kotlin extension in a class file?


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.


Solution

  • 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")
            }
        }
    }