6

The Idioms section of the official Kotlin docs contains this example:

Builder-style usage of methods that return Unit

fun arrayOfMinusOnes(size: Int): IntArray {
    return IntArray(size).apply { fill(-1) }
}

As the function apply returns the generic type, and I thought Unit is as same as void in Java, this section is suggesting we can use a void method in builder-style? That doesn't make sense to me - what's it trying to say?

Mark Amery
  • 127,031
  • 74
  • 384
  • 431
ShangXubin
  • 101
  • 3

2 Answers2

6

The point it's trying to make is that if you just did traditional Java builder style, like this:

return IntArray(size)
    .fill(-1)

then it wouldn't compile, because it's of type Unit, not IntArray. So traditionally, you'd have to do something like this:

val ret = IntArray(size)
ret.fill(-1)
return ret

apply enables you to avoid this, because the return type is still of type IntArray (or T, in general).

Oliver Charlesworth
  • 260,367
  • 30
  • 546
  • 667
1

Take this one:

class X {
    var a: Int? = null
    var b: Int? = null
    fun first(a: Int) = apply { this.a = a }
    fun second(b: Int) = apply { this.b = b }
}

X().first(2).second(3)

The apply functions are used to return the instance of X after setting the property. This enables builder-style call of both methods. If apply were removed, the function would return Unit.

s1m0nw1
  • 67,502
  • 14
  • 150
  • 189