Is there a more kotlinish version for this? ```val...
# getting-started
p
Is there a more kotlinish version for this?
Copy code
val list: List<Int> = someCalculation()
if(list.isNotEmpty()) { doSomethingWith(list) }
The only downside of the above is that you have to declare a list variable. (I like how you can use apply and avoid creating local variables )
s
Copy code
someCalculation().takeIf { it.isNotEmpty() }.let { doSomethingWith(it) }
2
🤦 1
r
@Sam it should be
?.let { ... }
if
doSomethingWith
should only be executed when the list is not empty
v
You miss a
?
otherwise you call the method with
null
if the list is empty
s
Ohhh, gotcha 👍 thanks!
Copy code
someCalculation().takeIf { it.isNotEmpty() }?.let { doSomethingWith(it) }
1
p
Ohh, thanks. works, but I guess it is worth to write some custom extension function then to make it clearer.
Copy code
someCalculation().runIfNonEmpty { doSomethingWith(this) }
1
y
Copy code
someCalculation().ifNotEmpty { doSomethingWith(it) }
Edit: seems like I had a false memory that this exists lol
s
👍 I've seen some YouTrack tickets for
ifNotEmpty
and also for a more generic
runIf
function. Seems like there's a gap here.
r
ifNotEmpty
might be confusing seeing as there is already an
ifEmpty
extension function on
Collection
that returns a default value if the list is empty
s
Well,
ifNotEmpty
could return a value too, even if it doesn't end up being used in all scenarios
r
that's true of course, if the intent of the functions is clear and consistent across
ifEmpty
and
ifNotEmpty
, I am in favour 🙂
m
off-topic: in this case I would put ifEmpty check inside
doSomethingWith
(e.g. if empty then return - guard clause) or make it work gracefully with empty collection.
plus1 1
🚫 1
p
True, but actually doSomething is a
sendNotification(SomeDto(it.map{ e -> e.id }))
, where sendNotifiation can handle many types of notifications, and SomeDto is just a DTO class.
o
I argue that your original code is already the most Kotlin Kotlin, unless this example of yours is somewhere in the middle of a chain. A simple
if
expression is the cleanest, most understandable, most concise and most straightforward version of this kind of code that you can write. No need for the ballast of higher order wrappers just for conditional execution.
💯 1
👍 2
3
p
Maybe, but then what about
let
? This case is just the generalization of let.
Copy code
val x = maybeNull?.let { process(this) }
vs
Copy code
val y = maybeEmpty.letNotEmpty { process(this) }
No separate type for nonempty collection though...
v
He meant 'use neither "let" nor "letNotEmpty" but keep the "if" you showed in your original post'.
More a matter of taste I'd say, though. 🙂
o
☝️ That is for sure, and my bike's shed will be a nice dark green, thank you very much.