2

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.

Pixel Elephant
  • 20,649
  • 9
  • 66
  • 83
Algar
  • 5,734
  • 3
  • 34
  • 51
  • 1
    Isn't the swift code equivalent to putting `class Jazz` and `fun Jazz.swing() {}` within the same Kotlin file? – BakaWaii Aug 30 '17 at 07:13
  • Why would you use an extension and don't just add the function as an ordinary one inside the class? – s1m0nw1 Aug 30 '17 at 07:21
  • @BakaWaii Yes, apparently it is :). I swear that I've tried that before with no luck :P. – Algar Aug 30 '17 at 07:26
  • You may also put what you've tried in the question next time and show what is the error you get. So that, you may find your answer while you are typing your question :) – BakaWaii Aug 30 '17 at 07:30
  • @s1m0nw1 It has mainly to do with code clarity. You "always" wan't to separate chunks of functions/code that has to do with a specific task. Remember that this can be multiple extensions on the same class. A small gain can also be if you have a set of private functions - then you can make the extension private and that is more clear than having lots of individually private methods in the class.. And at least in Swift, with Structs, you have a thing with default constructors that you avoid with extensions. Not sure if the same goes for Kotlin. – Algar Aug 30 '17 at 07:31
  • @BakaWaii That's a perfectly valid comment :). – Algar Aug 30 '17 at 07:32

2 Answers2

2

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")
        }
    }
}
guenhter
  • 11,255
  • 3
  • 35
  • 66
  • Thanks! I'm still missing an `extension` keyword though. Maybe in the bright Kotlin-future. – Algar Aug 30 '17 at 07:34
1

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
}
Alex Romanov
  • 11,453
  • 6
  • 48
  • 51