Thread
#effective-kotlin
    Fudge

    Fudge

    3 years ago
    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
    class User(val name: String,val email:String)
    They do
    class User{
    var name : String 
    var email: String
    }
    fun user(init: User.() -> Unit) = User.apply{init()}
    What are the benefits of this?
    t

    thana

    3 years ago
    i don't actually see any befinits in this simple case except on one. Im currently writing code like
    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
    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 😉
    Fudge

    Fudge

    3 years ago
    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

    3 years ago
    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