Kotlin / kotlin-style-guide

Work-in-progress notes for the Kotlin style guide
288 stars 14 forks source link

One-liner assignment methods #28

Open voddan opened 8 years ago

voddan commented 8 years ago

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 commented 8 years ago

1) One-liner:

fun mutateX(d: Int) { x += d }
voddan commented 8 years ago

2) With lambda:

fun mutateX(d: Int) = run { x += d }
voddan commented 8 years ago

3) Java-style:

fun mutateX(d: Int) {
    x += d
}
voddan commented 8 years ago

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)