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

Bruno Garcia

09/16/2019, 6:45 PM
Is there a way to instantiate an object while setting some properties on it? As an expression like:
Copy code
val a = Some() { b = "value" }
Or do I need multiple lines for that
s

streetsofboston

09/16/2019, 6:46 PM
What about
val a = Some(b = "value")
?
s

Shawn

09/16/2019, 6:46 PM
if the properties aren’t in the primary constructor and are public `var`s (and you don’t control this class), you could just
val a = Some().apply { b = "value" }
👍 1
b

Bruno Garcia

09/16/2019, 6:47 PM
❤️
thanks, looks great
s

Shawn

09/16/2019, 6:49 PM
given the caveats I mentioned I don’t know that it’ll necessarily solve the problem
but if works, great the constructor approach lets you set properties that are `val`s (assuming you have them defined in the primary ctor) and allow the parameters to be private instead
b

Bruno Garcia

09/16/2019, 7:19 PM
it’s all val. I don’t have an explicit contructor. The class is written in Java
I’m writing tests in Kotlin
m

Mike

09/17/2019, 3:33 PM
If
Some
is Java, then
apply
is the way to go.