Pihentagy
10/02/2024, 7:31 AMval 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
)Sam
10/02/2024, 7:32 AMsomeCalculation().takeIf { it.isNotEmpty() }.let { doSomethingWith(it) }
Riccardo Lippolis
10/02/2024, 7:37 AM?.let { ... }
if doSomethingWith
should only be executed when the list is not emptyVampire
10/02/2024, 7:38 AM?
otherwise you call the method with null
if the list is emptySam
10/02/2024, 7:38 AMSam
10/02/2024, 7:38 AMsomeCalculation().takeIf { it.isNotEmpty() }?.let { doSomethingWith(it) }
Pihentagy
10/02/2024, 7:42 AMsomeCalculation().runIfNonEmpty { doSomethingWith(this) }
Youssef Shoaib [MOD]
10/02/2024, 9:03 AMsomeCalculation().ifNotEmpty { doSomethingWith(it) }
Edit: seems like I had a false memory that this exists lolSam
10/02/2024, 9:05 AMifNotEmpty
and also for a more generic runIf
function. Seems like there's a gap here.Riccardo Lippolis
10/02/2024, 9:07 AMifNotEmpty
might be confusing seeing as there is already an ifEmpty
extension function on Collection
that returns a default value if the list is emptySam
10/02/2024, 9:07 AMifNotEmpty
could return a value too, even if it doesn't end up being used in all scenariosRiccardo Lippolis
10/02/2024, 9:09 AMifEmpty
and ifNotEmpty
, I am in favour 🙂Marian Schubert
10/02/2024, 10:09 AMdoSomethingWith
(e.g. if empty then return - guard clause) or make it work gracefully with empty collection.Pihentagy
10/02/2024, 11:34 AMsendNotification(SomeDto(it.map{ e -> e.id }))
, where sendNotifiation can handle many types of notifications, and SomeDto is just a DTO class.okarm
10/02/2024, 12:13 PMif
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.Pihentagy
10/02/2024, 12:52 PMlet
? This case is just the generalization of let.
val x = maybeNull?.let { process(this) }
vs
val y = maybeEmpty.letNotEmpty { process(this) }
Pihentagy
10/02/2024, 12:55 PMVampire
10/02/2024, 1:14 PMVampire
10/02/2024, 1:15 PMokarm
10/02/2024, 1:16 PM