kotlin-style-guide icon indicating copy to clipboard operation
kotlin-style-guide copied to clipboard

One-liner assignment methods

Open voddan opened this issue 8 years ago • 4 comments

How should a method be formatted which contains a one-line assignment? Use cases:

// mutating methods:
var x = 0
fun mutateX(d: Int) {
    x += d
}

// trivial custom property setters
var y = 0
    set(v) {
        y = v
    }

I want to openly discuss/vote on three solutions to choose the preferred one:

voddan avatar Jul 01 '16 14:07 voddan

  1. One-liner:
fun mutateX(d: Int) { x += d }

voddan avatar Jul 01 '16 14:07 voddan

  1. With lambda:
fun mutateX(d: Int) = run { x += d }

voddan avatar Jul 01 '16 14:07 voddan

  1. Java-style:
fun mutateX(d: Int) {
    x += d
}

voddan avatar Jul 01 '16 14:07 voddan

The current workaround is to fall back to explicit method invoketions instead of operators (for collections):

var arr = arrayOf(0, 0, 0)

fun inc1(i: Int) {
    arr[i] += 1
}

fun inc2(i: Int) = arr.set(i, arr[i] + 1)

voddan avatar Jul 01 '16 14:07 voddan