can takeif be used instead of a normal if else in ...
# announcements
x
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
foo.takeIf { !condition } ?: foo.filter{...}
n
i thought takeIf takes a predicate
you probably need braces instead of parens?
p
that’s right. Do
{ }
around it. but it doesn’t look great, at least in this small example (updated the code example)
x
sometimes i wonder where traditional ifs are a better fit
thank you 🙂
n
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
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
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
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
I don't think I follow that
collection?
t
filters operate on collections, I'm assuming
foo
is therefore some type of collection
x
got you, im keeping an if i think
k
In this case a normal
if
is prefered
a
foo.takeIf { condition }?.filter {} ?: foo
n
@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
nvm, I'm relatively new to Kotlin and I was confusing it with
takeWhile
117 Views