https://kotlinlang.org logo
f

Fudge

06/21/2019, 7:40 PM
I've been seeing all these libraries using type-safe builders in a way that seems insane It basically goes like this (as a simplified example): Instead of having
Copy code
class User(val name: String,val email:String)
They do
Copy code
class User{
var name : String 
var email: String
}
fun user(init: User.() -> Unit) = User.apply{init()}
What are the benefits of this?
t

thana

06/24/2019, 7:53 AM
i don't actually see any befinits in this simple case except on one. Im currently writing code like
Copy code
class SomeClass{
    companion object{
        fun from(someOther: SomeOther): SomeClass {
          // create an instance from someOther
        }
    }
}
Now, if
SomeClass
can be initialized with a builder the
from
method can be re-written like
Copy code
fun from(someOther: SomeOther) = SomeClass {
}
Here i can do really more than just creating an instance as i can use some conversion logic which is more complex than just passing some references which might be more pleasant for some programmers' eyes to be done in an expression-style block than just a normal block 😉
f

Fudge

06/24/2019, 12:20 PM
But in cases where you are merely passing a string or an enum... I've talked to a library author and he said that using plain old parameters is 'a step back in API design'
t

thana

06/26/2019, 2:26 PM
Maybe a reason could be to always use the same approach to construct objects. But using it because otherwise your design is too old? I couldn't disagree more
9 Views