arve
07/31/2020, 12:49 PM// fun src.loadString(fieldName: String): String? {...}
dstBuilder.fieldA = src.loadString("aField") ?: throw Exeption("Field A is not present")
// Instead of throwing, i want to leave dst.fieldA unset - skip this line and move to next.
Javier
07/31/2020, 12:56 PMTim VanFosson
07/31/2020, 1:03 PMsrc
value for aField
is null?Lars Wenning
07/31/2020, 1:19 PMsrc.loadString("test")?.let { loadedString -> dst.fieldA = loadedString}
The code inside let() will only be called if loadString is not null, otherwise dst.fieldA remains unchangedarve
07/31/2020, 1:29 PMarve
07/31/2020, 1:30 PMgian
07/31/2020, 1:31 PMsrc.loadString("aField")?.let(dstBuilder::fieldA::set)
Not sure how recommended it isTim VanFosson
07/31/2020, 1:35 PMthrow
on a missing field - now you're getting stale or missing data instead. Downstream code may assume that new values have been loaded. Yeah, the code maybe prettier, but it's not equivalent.arve
07/31/2020, 1:47 PMif(source.hasProperty("name-A") builder.fieldA = source.getProperty("name-A")
if(source.hasProperty("name-b") builder.fieldA = source.getProperty("name-b")
// (...)
Tim VanFosson
07/31/2020, 1:47 PMStian N
07/31/2020, 1:53 PMsrc.loadString("aField")?.let { dst.fieldA = it }
Tim VanFosson
07/31/2020, 1:55 PMDaniel
07/31/2020, 1:57 PMsource.hasProperty("name-b")
in a variable newB
and keep the assigment in the ìf
.
In my opinion that is more clear than using let
. At least I would have to think a bit longer about the code when its using the let
.
But not a fan of ?.let
in generalDaniel
07/31/2020, 2:05 PMdstBuilder.fieldA = src.loadString("aField") ?: dstBuilder.fieldA
But of course then you repeat dstBuilder.fieldA
okarm
07/31/2020, 2:09 PM?.let
?
I am a huge fan of using ?.let
in single expression functions, like the following ORM type converter:
fun toBigDecimal(bd: String?): BigDecimal? = bd?.let(::BigDecimal)
Daniel
07/31/2020, 2:16 PMbd?.let(::BigDecimal)
when I see it (and when the function is not so nicely named.
Second is that introduces it
which is more often than not kept as a name.
Don't get me wrong. ?.let
is perfectly fine when used sparsely. But I have seen code when lets where used inside lets and all without renaming it
. You don't need code obfuscation then!
Thats why I always prefer:
if(xyz == null) return
doStruff with xyz
When its possible.
Keeps things flat and for me its immedeately clear what is happening at first glanceStian N
07/31/2020, 2:23 PMit
if the logic is short and sweet, like in the example above. If it becomes more complicated, and always when nesting, I will give it a describing name.Bornyls Deen
07/31/2020, 4:01 PMdstBuilder.fieldA = src.loadString("aField") ?: dstBuilder.fieldA
I'd probably stick with something like this as others have suggested.
src.loadString("aField")?.let { field ->
dstBuilder.fieldA = field
}