One last thing

Builder objects were mentioned earlier. If we need to do so, Kotlin makes our life a lot easier. There are two features that help us with this pattern: named arguments and default arguments.

One of the issues the Builder Pattern solves is that when having a large number of parameters, it’s hard to follow what’s what (specially if their type is the same). Look at the constructor of Rect :

Rect(10, 30, 30, 40)

It’s not very clear what each value represents. Some IDEs like IntelliJ and Android Studio help by adding small labels to each of the parameters. However, that luxury is not always available (GitHub for instance).

Unfortunately, we can’t use named arguments on non-Kotlin classes. If you are fortunate of working with a Kotlin codebase, you can create an object like this:

KRect(

left = 10,

top = 30,

right = 30,

bottom = 40

)

Much easier to read and quite similar to a builder object.

Another useful feature of Builders is that you can leave some parameters as optional. Here is where default parameters become rather useful:

class KRect(

val left: Int,

val top: Int,

val right: Int = left,

val bottom: Int = top

)

Here we are making right and bottom take the value of left and top . So if we only provide two values we have a point:

KRect(

left = 10,

top = 30

)

It’s possible to also have hardcoded values:

class KRect(

val left: Int,

val top: Int,

val right: Int = -1,

val bottom: Int = -1

)

This pattern can help you create interesting Objects without so much boiler plate code. The one aspect that can cause some trouble is that the client can decide to ignore the named methods and use your function/constructor in the old way. Some may argue that it gives them more freedom though.

Could be worse though, they could be using mid-function returns.