loading...

Discussion

markdown guide
 

The Builder pattern in Kotlin is somewhat of an anti-pattern, as there are a lot of language features that make Builders redundant.

You can define default values in constructors, allowing consumers of your API to return fully-functional objects without having to pass dozens of different values - instead specifying what they want to change. This in essence is what a Builder allows you to do anyway:

If you really want a Builder, the more idiomatic way is to write a DSL, which is basically decoration ontop of a traditional Builder:

Again you can set default values, but this time you do it within the Builder itself. It's much more Kotlin-y, and if you want you can add assertions to ensure that certain functions are always called/set.

 

Thanks Adam.
I'm new to kotlin. I'm just curious about this things. I think Kotlin is a great language because it has some cool features. my favorite one is function or construtor with default parameter and extension. Move from java to kotlin is somewhat a great experience. So i think we don't need builder pattern in kotlin.