https://kotlinlang.org logo
Title
h

Hullaballoonatic

10/31/2019, 6:21 PM
anyone ever wish there was a clean way to do
else ""
,
else 0
, etc?:
return myStr + if (myCondition) myPostfix else ""
return myVal + if (myCondition) myAddition else 0
obviously the nicest syntax would probably simple exclude the
else
, but that of course does not compile
k

karelpeeters

10/31/2019, 6:33 PM
I'm frustrated every time I have to write
if(c) x else ""
too!
d

David Silva

10/31/2019, 6:33 PM
Yep, I’m not really aware of Java APIs anymore, but we could use the ternary operator which some might consider easier to read
return myStr + myCondition ? myPostfix : ""
Anyway, It might help if you move the suffix computation to its own function 🤷‍♂️
return myStr + computeSuffix()
..
private fun computeSuffix() = if (myCondition) mySuffix else ""
h

Hullaballoonatic

10/31/2019, 6:34 PM
i could write a function like
fun String.appendIf(cond: Boolean, postFix: String)
but that's even more wordy in use and less readable
a

Alowaniak

10/31/2019, 6:34 PM
Does
myStr + (myPostfix.takeIf { myCondition } ?: "")
work?
s

Shawn A

10/31/2019, 6:34 PM
fun <T> Boolean.whenTrue(value: T, otherwise: T): T {
    return if(this) value else otherwise
}
😆
Sometimes simplest is best though. I'd scratch my head if someone used that @Alowaniak
h

Hullaballoonatic

10/31/2019, 6:39 PM
yeah, that would work, but it is also equally verbose as an if/else expression while being less readable
a

Alowaniak

10/31/2019, 6:41 PM
Hmyea I guess so If it were "unless" I kinda feel like it would make sense natural language wise
h

Hullaballoonatic

10/31/2019, 6:42 PM
to be clear, the topic isn't about ternary expressions, it's about "else nothing"
l

Luke

10/31/2019, 6:52 PM
fun String.emptyIf(condition: Boolean) = if (condition) "" else this
? So you would have
return myStr + myPostfix.emptyIf(condition)
h

Hullaballoonatic

10/31/2019, 6:54 PM
yeah, not a bad idea i'll probably just write:
fun String.given(condition) = if (condition) this else ""
or for the opposite:
fun String.unless(condition) = if (condition) "" else this
fun String.unless(condition: (String) -> Boolean) = if (condition(this)) "" else this
is nice too
l

Luke

10/31/2019, 7:01 PM
The name does not imply that it is an empty String that is returned though. I was going for something in between `takeIf`/`takeUnless` and
orEmpty()
k

karelpeeters

10/31/2019, 7:15 PM
Sometimes if it's part of a bigger string building system you can conditionally append too:
buildString {
    if (cond) append(str)
}
h

Hullaballoonatic

10/31/2019, 7:31 PM
i think the name of the functions are enough context given they're called alongside concatenation or other operations