Kotlin Website Link
The website said
"Builder-style usage of methods that return Unit"
fun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}
As function "apply" returns the generic type, and I thought Unit is as same as void in Java, so use a void method as a builder-style, it doesn't make sense.
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).
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
.