kotlin-style-guide
kotlin-style-guide copied to clipboard
One-liner assignment methods
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:
- One-liner:
fun mutateX(d: Int) { x += d }
- With lambda:
fun mutateX(d: Int) = run { x += d }
- Java-style:
fun mutateX(d: Int) {
x += d
}
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)