re: Gang of Four Patterns in Kotlin VIEW POST


Really good post. short and clean - like as a Kotlin style ;)
But i think builder could be opened more. Your example is good, but i mean the using of builder is much more then just setting of a properties. Most interesting example, is then u want to pass some code like as parameter. Something from my DSL for selenium SeleniumBuilder:

inline fun <T : WebDriver> driver(driver: T, init: T.() -> Unit) {
    try {
    } finally {

Or more colorful example, like as u show, if u want to calc execution time of some code:

inline fun calcExecTime(init: () -> Unit): Float {
    val start = System.nanoTime()
    return (System.nanoTime() - start) / 1000000000F
val resultTime = calcExecTime {
    // do anything here

thank you!

yeah, those type save builders / DSLs are nice. But they are a topic on their own, and and wanted to keep it "basic" :-)

I would not consider calcExecTime a builder, since it does not create anything.

btw a method like this already exists in the standard lib - its called measureTimeMillis :-)


actually yes, its build nothing) sorry for disorientation, but I want to show many other features, who can be provided by lambda with receiver.


Using apply for post constructor changes is nice but I wouldn't call it a builder. With the approach you are describing an instance is created first, with empty constructor, and then modified in the apply{} block. This means that

  1. Default values are required

  2. It is not possible to ensure that an instance exists only if the parameters are valid

code of conduct - report abuse