Given a boolean condition I want to return an obje...
# announcements
g
Given a boolean condition I want to return an object if that expression returns
true
. Is there a shorter way (in the stdlib maybe) to write the following?
someBooleanCondition.takeIf { true }?.let { "dummy-string" }
E.g. (in pseudo-code)
someBooleanCondition.ifTrue { "dummy-string" }
d
What's wrong with an if-expression?
if (someCondition) "dummy-string" else null
5
but if you insist...
"dummy-string".takeIf { someCondition }
g
Nothing wrong with it, thanks for the answers
w
Did not test, but maybe something like:
Copy code
inline fun <T> Boolean?.ifTrue(asas: (Boolean) -> T): T? = this?.takeIf { it == true }?.let(asas)
Then maybe use as you want:
Copy code
val b = true
        val r: String? = b.ifTrue { "asas" }
g
I'll just go with a normal if-expression then. I don't want to introduce an
ifTrue
extension if it's not already there in the stdlib
d
takeIf
is that extension, you just have to swap condition and the value you want.
👍 1
t
also, imo extension functions are exactly made for that purpose: extend library behaviour with your own needs
👍 2
g
Imo if/else is much better solution, not just because it standard and easy to understand, but also because it much easier to extend, if at some point you want to add else value it would look really clumsy with elvis operator and it would require to rewrite this expresdion completely if you add one more case to it ( like if/else if/else)
👍 3
g
imo,
takeIf
has its own usage in chains, no need to overthink in simple cases, where
if
is expressive enough.
👍 3
r
if
would be better if we had a ternary operator...
🚫 1