i’m curious what people’s opinions are about the k...
# arrow
p
i’m curious what people’s opinions are about the kotlin builder pattern DSL, eg: https://github.com/ktorio/ktor/blob/main/ktor-server/ktor-server-core/jvm/src/io/ktor/server/util/URLBuilder.kt#L31 using: https://github.com/ktorio/ktor/blob/main/ktor-http/common/src/io/ktor/http/URLBuilder.kt mutable state as far as the eye can see 🙂 but the actual DSL function
url
has mutable state constrained locally and should still be referentially transparent i believe, does this pattern have a place in functional kotlin?
e
I think it's incredibly useful. As you say, the mutability is constrained and I don't really see a problem with it..
👍 1
r
hi @Peter, if the mutability is constrained to the building process and does not scape the scope of the builder I think it’s fine. In this case it may come down to style. I would personally not place
public var
like this because mutability would escape the original definition allowing all
var
properties accesible for mutation outside if you pass builder as return or argument value to other functions. I believe the same can be accomplished with constructors and default value arguments without leaking the mutable pieces. For example:
Copy code
public var encodedUser: String? = user?.encodeURLParameter()
public var user: String?
        get() = encodedUser?.decodeURLPart()
        set(value) {
            encodedUser = value?.encodeURLParameter()
        }
may be expressed as
Copy code
public class URLBuilder(
    private user: String?,
    val encodedUser: String? = { user -> user?.encodeURLParameter() }
) {
  val user: String? = encodedUser?.decodeURLPart()
}
IMO If the answer is just to give user
=
syntax inside the block, it’s questionable if better ergonomics that can potentially leave the door open to incorrectness is worthy. Do you have a particular model in mind or is this in general for any builder?
p
hi @raulraja - thank you for the thoughts, agreed, one would have to be careful, I think this particular example is ok returning an immutable value, state shouldn’t be escaping anywhere but it could easily happen using this model. I was just wondering in general, the ergonomics are quite clean but I also wondered about the possible tradeoff in safety..