Czar
12/08/2019, 4:56 PMif(x != null) y = x
vs x?.let { y = x }
vs custom ifNotNull(x) { y = it }
vs y = x ?: y
? (I know, that the last one is not 100% equivalent to others as in case of property it invokes setter in any case)adimit
12/08/2019, 6:10 PMkarelpeeters
12/08/2019, 6:32 PM{}
to the case.
I've never seen the last one, feel weird to me.Anastasia Finogenova
12/08/2019, 9:29 PMghedeon
12/09/2019, 12:33 AM.let
applications.let
is, it's easier to add else
to the if
version and it'll look more readable.Anastasia Finogenova
12/09/2019, 1:06 AMShawn
12/09/2019, 4:53 AMif (x == null)
is far more readable and expressive than x?.let { }
Czar
12/09/2019, 7:00 AMclass MyEntity {
val id: Long? = null
var prop1: String? = null
var prop2: String? = null
// ...
var propN: String? = null
}
and an update command:
class UpdateEntityCommand {
val myEntityId: Long
var prop1: String? = null
var prop2: String? = null
// ...
var propN: String? = null
}
the handler should only change property of the entity if corresponding property of the command is not null
:
class MyHandler(private val repo: MyEntityRepository) {
fun execute(command: UpdateEntityCommand) {
with(repository.getOne(command.myEntityId)) {
if (command.prop1 != null) prop1 = command.prop1 // (1)
command.prop2?.let { prop2 = it } // (2)
ifNotNull(command.propN) { propN = it } // (3)
}
}
}
By the way, detekt hates (2), and I have to @Suppress("ComplexMethod")
Anastasia Finogenova
12/09/2019, 6:00 PMShawn
12/09/2019, 6:10 PMif
statements “in every method” are just as noisy, if not noisier considering it’s less intuitive to read, and are potentially confusing if you’re doing anything side-effect-ey in the lambda. there are definitely times where let fits in well, e.g. chained monadic operations on a nullable, but this is not one of them. if you find yourself needing to something in a procedural way, I see no point in bending functional constructs to do sokarelpeeters
12/09/2019, 10:21 PM