https://kotlinlang.org logo
Title
j

Jan

02/06/2022, 5:54 PM
I'm not sure when exactly I'd use a value class. Does it make sense for something like this: (see thread)?
class SelectionMenuOptionBuilder(val options: MutableList<SelectOption> = mutableListOf()) {

    fun option(label: String = "", value: String = "", description: String? = null, emoji: Emoji? = null, default: Boolean = false) { options += SelectOption(label, value, description, emoji, default)}
    fun add(selectOption: SelectOption) { options += selectOption }
    fun addAll(selectOptions: Iterable<SelectOption>) { options += selectOptions }
    fun addAll(selectOptions: Array<SelectOption>) { options += selectOptions }

}
k

Klitos Kyriacou

02/06/2022, 6:32 PM
This doesn't look like a builder. Conventionally a builder would create its own mutable list and have a
build()
function that returns an immutable
List
.
n

Nick Allen

02/06/2022, 6:43 PM
That’s Java builders, Kotlin builders are generally a single function that take a lambda where you can populate a mutable value or do other work and then they return an immutable value or other result. You could just use
buildList
m

Mike Sutjipto

02/06/2022, 7:39 PM
are you wondering if your builder class should be a value class? doesn't really feel like the typical usage of a value class - normally i would use it to wrap something like a string (or other primitive type) where I wanted the semantics of that value to be more clear and also involved in the type system. so e.g. something like
value class UserId(val value: String)
is a common way of using them (at least for me)
👍 1
👍🏻 1
m

Mykola Gurov

02/06/2022, 7:48 PM
SelectOption
could’ve been a good candidate for the data class. The builder we see here is just a convenience wrapper around the mutable list, and TBH I’m not sure I even see any added value here since the clients of this class could’ve just used the same
mutableList
directly
j

Jan

02/06/2022, 10:28 PM
Okay thanks