Jérémy CROS
10/12/2021, 3:31 PMdata class Foo(val a:Int, val b = 0)
val bar = Foo(a = 3, if(param) b = 5 /*else keep the default param */)
Is there an alternative other than val bar = if(param) Foo(...) else Foo(...)
Holden Easley
10/12/2021, 3:32 PMFoo(a = 3).let {
if (param) it.copy(b = 5) else it
}
??Jérémy CROS
10/12/2021, 3:39 PMConnor Ford
10/12/2021, 3:41 PMdata class Foo(val a: Int, val b: Int = DEFAULT_B) {
constructor(a: Int, p: Boolean): this(a, if (p) a else DEFAULT_B)
companion object {
private const val DEFAULT_B = 0
}
}
CLOVIS
10/12/2021, 5:23 PMephemient
10/12/2021, 5:56 PMStephan Schroeder
10/13/2021, 7:24 AMdata class Foo(val a:Int, val b = 0)
val bar = if(param) {
Foo(3, 5)
} else {
Foo(3)
}
ephemient
10/13/2021, 7:33 AMwith(Foo::class.primaryConstructor!!) {
callBy(listOfNotNull("a" to 3, if (param) "b" to 5 else null).associate { (name, value) -> parameters.single { it.name == name } to value })
}
:blob-thinking-upside-down:Foo::class.java
.getDeclaredConstructor(Int::class.java, Int::class.java, Int::class.java, kotlin.jvm.internal.DefaultConstructorMarker::class.java)
.newInstance(3, if (param) 5 else 0 /* this value doesn't matter */, if (param) 0 else 2 /* bitmask */, null)
Alex
10/13/2021, 8:34 AMJérémy CROS
10/13/2021, 9:19 AMreturn ActionInfrastructureUntilLevel(
buildAction(instructionHumanized.humanInstruction.action),
buildDirectionalInfrastructure(
instructionHumanized.humanInstruction.infrastructure
),
infrastructureUntilLevel.level,
infrastructureUntilLevel.label
).let {
if (isFirstInstructionAnInfrastructure)
it.copy(template = R.string.sentence_template_infrastructure_until_level_first)
else it
}
it’s basically a sentence builder with optional template parameter that are later used for translation.
In that case, the simple if else as suggested by @Stephan Schroeder looks worse, IMO
Won’t comment on @ephemient trolling me though 😛ephemient
10/13/2021, 9:27 AMJérémy CROS
10/13/2021, 9:29 AM