kotlinself-documenting-code

Does Kotlin have method-CALL labels?


I'm moving from Swift to Kotlin, and loving it so far. However, I'm used to declaring methods like this (pretend the referenced methods exist and work):

// Swift method declaration
func drawCircle(inRect rect: CGRect, antialiased: Bool) {
    super.antialiased = antialiased
    super.drawCircle(inRect: rect)
}

and calling them like this:

drawCircle(inRect:myRect, antialiased: false)

which is beautifully self-documenting and reads like English. However, in Kotlin, a similar method like this:

fun drawCircle(inRect: Rectangle, antialiased: Boolean) {
    super.antialiased = antialiased
    super.drawCircle(inRect)
}

which already starts to sound odd using a variable named inRect. But then it gets worse when I call it:

drawCircle(myRect, false)

and here we see the biggest problem: One can likely guess by reading this line alone that myRect is a rectangle in which the circle will be drawn. However, what is true? It could be antialiasing, yes, but it could also be whether to draw it opaquely, or some toggle about whether to draw it at all! Anyway, I could cite more reasons why Swift and Objective-C programmers love their labels with method calls, but I've made my point.

Is there any way to enable labels on method call in Kotlin?


Solution

  • As far as I know, there's no compiler option to force this syntax, but you can still use it in your code, see the docs: Named arguments.

    To say it short, the syntax for your function is

    drawCircle(inRect = myRect, antialiased = false)
    

    You can even change function arguments order in a call using named arguments.

    drawCircle(antialiased = false, inRect = myRect)
    

    The limitations are: