Kotlin builders (?)

First, are there any good builder generators out there?

Second, what would be the recommended syntax and I’d like to use 1-line chains:

    fun setId(id: String?): Builder

or

    fun id(id: String?): Builder

So, I don’t interfere/confuse the internal setter mechanisms (especially for data classes).

Here is an example how to create “fancy” builders using DSLs.

3 Likes

Another easy way to create Builders is to use the scope functionapply’ in a Syntax like this:

val adam = PeopleBuilder().apply {
    name = "Adam"
    age = 32
    city = "London"        
}.build()
println(adam)

Its also nice for interop with Java Builders while using a Kotlin like Syntax.

4 Likes

In the end, it is hard to beat the copy constructor for brevity and flexibility.

data class Person(
    val name: String,
    val address: Address? = null,
    val phone: String? = null
)

val jenna = Person("Jenna")

val withMoreData = jenna.copy(
    address = Address(...),
    phone = "(555) 555-1212"
)

If you want to do something fancy in a “setter”:

fun Person.withAddress(addressString: String) = 
    copy(address = addressString.toAddress())
3 Likes

Sure but that’s no longer possibel if your data class looks like this

data class Person(
    val name: String,
    val address: Address,
    val phone: String
)

val jenna = error("can't create empty Person")

val withMoreData = jenna.copy(
    name  = "Jenna",
    address = Address(...),
    phone = "(555) 555-1212"
)