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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With