karelpeeters
07/24/2017, 7:37 PMfun main(args: Array<String>) {
val map = mutableMapOf<String, Int>()
val lst = mutableListOf<Int>()
map["answer"] = 42
for (arg in args) {
map[arg]?.let {
lst.add(it)
}
}
}
baermitumlaut
07/24/2017, 7:39 PMdalexander
07/24/2017, 7:41 PMmap[arg]?.let { ... } ?: <stuff to do when it's null>
which may or may not look better to you.karelpeeters
07/24/2017, 7:42 PMdalexander
07/24/2017, 7:45 PMbaermitumlaut
07/24/2017, 7:47 PMfor (arg in args) {
map[arg]?.let {
lst.add(it)
}?: {
lst.add(0)
}
}
karelpeeters
07/24/2017, 7:47 PM?: run {...}
or ?: {...}()
karelpeeters
07/24/2017, 7:48 PMdalexander
07/24/2017, 7:49 PMrun
is better in my opinion. Or you could refactor your contingency plan into its own method and call that depending on what kind of local context you need.baermitumlaut
07/24/2017, 7:50 PMRuckus
07/24/2017, 7:54 PMsomeFun()?.let {
...
} ?: run {
...
}
is so much less clear than just
val someVal = someFun()
if (someVale != null) {
...
} else {
...
}
Sure it's technically a one liner, but Kotlin was designed to be clear, concise, and explicit, not cryptic 😛Ruckus
07/24/2017, 7:55 PMnull
in the let
block will also run the run
block in the first example)karelpeeters
07/24/2017, 7:58 PMRuckus
07/24/2017, 8:00 PMdalexander
07/24/2017, 8:04 PMapply
instead of let
and avoid that trap?karelpeeters
07/24/2017, 8:05 PMapply
doesn't work, that uses the extension function thing. also
works nicely though.karelpeeters
07/24/2017, 8:06 PMlet
is an idiom at all...dalexander
07/24/2017, 8:06 PMapply
should work because it returns the receiver ie. null or not null, rather than the result of the closure you pass in.karelpeeters
07/24/2017, 8:07 PMapply
isn't a drop-in replacement for let
, the it
-syntax doesn't work.karelpeeters
07/24/2017, 8:08 PMalso
is one.dalexander
07/24/2017, 8:09 PMthis
in apply.Ruckus
07/24/2017, 8:10 PM?.let { ... }
, but usually only when it actually returns a value, not as a shortcut to if
. Though it's just a personal preference.Ruckus
07/24/2017, 8:10 PMlet
has always been in the language, whereas also
is relatively new, so it became the idiom.karelpeeters
07/24/2017, 8:10 PMlet
is useful.karelpeeters
07/24/2017, 8:11 PMRuckus
07/24/2017, 8:13 PMkarelpeeters
07/24/2017, 8:16 PMlet
would do. Same for also
...