Colton Idle
01/05/2024, 1:51 PMhfhbd
01/05/2024, 1:52 PMthis
or do you get a new builder after each .addX()
? If mutable, just use apply
Colton Idle
01/05/2024, 1:57 PMPablichjenkov
01/05/2024, 1:59 PMColton Idle
01/05/2024, 2:01 PMPablichjenkov
01/05/2024, 2:03 PMColton Idle
01/05/2024, 2:05 PMKlitos Kyriacou
01/05/2024, 2:37 PMapply
method worked as you intended. If each builder method returns a new builder, then using apply
will work but you won't actually build anything.
This is what happens:
val obj = SomeBuilder().apply {
if (cond1) addA() // returns a new instance, which gets discarded
addB() // returns another new instance, which gets discarded
build() // builds the original empty object without addA or addB
}
Klitos Kyriacou
01/05/2024, 2:40 PMval obj = SomeBuilder()
.let { if (cond1) it.addA() else it }
.addB()
.build()
Albert Chang
01/05/2024, 2:53 PMColton Idle
01/05/2024, 2:55 PMColton Idle
01/05/2024, 2:55 PMColton Idle
01/05/2024, 2:56 PMKlitos Kyriacou
01/05/2024, 3:00 PMthis
, not a new object. For example: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/StrictMode.java#529Colton Idle
01/05/2024, 3:02 PMYoussef Shoaib [MOD]
01/05/2024, 3:15 PMrunIf
might be good here.
inline fun <T> T.runIf(condition: Boolean, block: T.() -> T): T = if(condition) block(this) else this
Edited to actually make it a run
🤦🏼♂️Daniel Pitts
01/05/2024, 3:37 PMblock: T.()->T
personally, since you won't need to use it.
in the lambda.Daniel Pitts
01/05/2024, 3:38 PMbuilder.runIf(someVersion) { useVersionFeature() }
Youssef Shoaib [MOD]
01/05/2024, 3:50 PMColton Idle
01/05/2024, 4:31 PMKlitos Kyriacou
01/05/2024, 4:36 PMthis
, we wouldn't be discussing this.Colton Idle
01/05/2024, 5:09 PM