Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The "Builder-style usage of methods that return Unit" on Kotlin website confuse me

Tags:

kotlin

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?

like image 888
ShangXubin Avatar asked Dec 23 '17 18:12

ShangXubin


1 Answers

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).

like image 153
Oliver Charlesworth Avatar answered Nov 15 '22 10:11

Oliver Charlesworth