https://kotlinlang.org logo
#codereview
Title
# codereview
b

Ben Madore

09/30/2021, 5:48 PM
i’ve got a class like:
Copy code
class MyFoo(
    val title:  String,
    val client: Foo = (some default)
) {...}
I want to provide a default value of Foo when if it’s not provided, but it’s nontrivial to create a valid instance, and requires storing an instance variable e.g.
Copy code
val x = Bar()
client = Foo.builder().bar(x).baz(Baz.builder().bar(x).build()).build()
i’m struggling to figure out if this is possible with initializer / secondary constructors, without having to make
client
a nullable
var
.
e

ephemient

09/30/2021, 6:02 PM
Copy code
class MyFoo(
    val title: String,
    val client = run {
        val x = Bar()
        Foo.builder().bar(x).Baz(Baz.builder().bar(x).build()).build()
    }
)
should work, but for something as complex you should probably have a
fun defaultClient(title: String): Foo
instead
s

sbyrne

09/30/2021, 6:04 PM
The default can come from a method call: e.g.:
val client:Foo = getDefaultClient()
, which could be a method in Foo's companion object, or anywhere else.
b

Ben Madore

09/30/2021, 6:05 PM
ah, welp, that makes sense
dunno how on earth i didn’t get to that myself, but… thanks!
4 Views