DEV Community

Discussion on: Send me all the Kotlin questions you were too afraid to ask

 
alexpi_31 profile image
Alejandro Pimentel

Hey, builder pattern is interesting....

I'm trying to understand this expression:

fun dialog(init: DialogBuilder.() -> Unit): Dialog =
DialogBuilder(init).build()

The part that is kind of weird to me is: DialogBuilder.()

Is that related to the extension functions?

Thread Thread
 
jmfayard profile image
Jean-Michel πŸ•΅πŸ»β€β™‚οΈ Fayard

So actually the builder pattern is integrated in Kotlin itself.

Given data class User(val id: Int = 1, val name: String = "")
Then this do the same as the builder pattern would do in Java
val user = User(name = "Alejandro", id =42)

The dialog function is a building block for building a DSL.
It takes as parameter a function init that you could define as having a parameter DialogBuilder and returning Unit. But instead you define the parameter as an extension function of DialogBuilder.

kotlinlang.org/docs/reference/lamb...