https://kotlinlang.org logo
#announcements
Title
# announcements
x

xii

07/17/2020, 5:47 PM
can takeif be used instead of a normal if else in the following code somehow?
Copy code
function foo() = if (condition) foo.filter{} else foo
i think i've seen it used somehow to decide whether to run the next inline function or not, but i can't remember
p

pedro

07/17/2020, 5:53 PM
foo.takeIf { !condition } ?: foo.filter{...}
n

Nir

07/17/2020, 5:55 PM
i thought takeIf takes a predicate
you probably need braces instead of parens?
p

pedro

07/17/2020, 5:56 PM
that’s right. Do
{ }
around it. but it doesn’t look great, at least in this small example (updated the code example)
x

xii

07/17/2020, 5:57 PM
sometimes i wonder where traditional ifs are a better fit
thank you 🙂
n

Nir

07/17/2020, 5:57 PM
Well, if you have both if and else branches
then it seems to me not obvious that takeIf/takeUnless will be an improvement
if you just have an if then it's simpler
p

pedro

07/17/2020, 5:58 PM
yeah, whenever I try to use
takeIf
, I think I end up undoing it. Partly because it’s not a common construct so present/future readers would find it a bit awkward to understand
n

Nir

07/17/2020, 6:01 PM
yeah, it seems liek for simply cases where you already have a variable, all you're doing is replacing one branching construct (if-else) with two (takeIf + ?:)
For me it seems more useful when the condition is complex, and might even involve intermediate variables that have no other use
t

Tim VanFosson

07/17/2020, 6:01 PM
note that if the condition isn't true you're still going to evaluate it for each element in the collection if you use
takeIf
I would not make this replacement.
n

Nir

07/17/2020, 6:02 PM
I don't think I follow that
collection?
t

Tim VanFosson

07/17/2020, 6:04 PM
filters operate on collections, I'm assuming
foo
is therefore some type of collection
x

xii

07/17/2020, 6:11 PM
got you, im keeping an if i think
k

Kroppeb

07/17/2020, 7:31 PM
In this case a normal
if
is prefered
a

Arkadii Ivanov

07/17/2020, 10:45 PM
foo.takeIf { condition }?.filter {} ?: foo
n

Nir

07/17/2020, 11:18 PM
@Tim VanFosson I'm not sure why you say that if the condition isn't true, you're still going to evaluate something still for each element of the collection
All of these things, ?:, ?. should be properly short circuiting
t

Tim VanFosson

07/18/2020, 1:32 PM
nvm, I'm relatively new to Kotlin and I was confusing it with
takeWhile
50 Views