https://kotlinlang.org logo
Title
g

Giorgio Antonioli

04/09/2019, 1:44 PM
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

diesieben07

04/09/2019, 1:46 PM
What's wrong with an if-expression?
if (someCondition) "dummy-string" else null
5
but if you insist...
"dummy-string".takeIf { someCondition }
g

Giorgio Antonioli

04/09/2019, 1:47 PM
Nothing wrong with it, thanks for the answers
w

wbertan

04/09/2019, 1:47 PM
Did not test, but maybe something like:
inline fun <T> Boolean?.ifTrue(asas: (Boolean) -> T): T? = this?.takeIf { it == true }?.let(asas)
Then maybe use as you want:
val b = true
        val r: String? = b.ifTrue { "asas" }
g

Giorgio Antonioli

04/09/2019, 1:49 PM
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

diesieben07

04/09/2019, 1:49 PM
takeIf
is that extension, you just have to swap condition and the value you want.
👍 1
t

thanksforallthefish

04/09/2019, 1:50 PM
also, imo extension functions are exactly made for that purpose: extend library behaviour with your own needs
👍 2
g

gildor

04/09/2019, 2:08 PM
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

ghedeon

04/09/2019, 2:12 PM
imo,
takeIf
has its own usage in chains, no need to overthink in simple cases, where
if
is expressive enough.
👍 3
r

ribesg

04/10/2019, 7:44 AM
if
would be better if we had a ternary operator...
🇳🇴 1