anyone ever wish there was a clean way to do `else...
# announcements
h
anyone ever wish there was a clean way to do
else ""
,
else 0
, etc?:
Copy code
return myStr + if (myCondition) myPostfix else ""
Copy code
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
I'm frustrated every time I have to write
if(c) x else ""
too!
d
Yep, I’m not really aware of Java APIs anymore, but we could use the ternary operator which some might consider easier to read
Copy code
return myStr + myCondition ? myPostfix : ""
Anyway, It might help if you move the suffix computation to its own function 🤷‍♂️
Copy code
return myStr + computeSuffix()
..
private fun computeSuffix() = if (myCondition) mySuffix else ""
h
i could write a function like
Copy code
fun String.appendIf(cond: Boolean, postFix: String)
but that's even more wordy in use and less readable
a
Does
myStr + (myPostfix.takeIf { myCondition } ?: "")
work?
s
Copy code
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
yeah, that would work, but it is also equally verbose as an if/else expression while being less readable
a
Hmyea I guess so If it were "unless" I kinda feel like it would make sense natural language wise
h
to be clear, the topic isn't about ternary expressions, it's about "else nothing"
l
fun String.emptyIf(condition: Boolean) = if (condition) "" else this
? So you would have
return myStr + myPostfix.emptyIf(condition)
h
yeah, not a bad idea i'll probably just write:
Copy code
fun String.given(condition) = if (condition) this else ""
or for the opposite:
Copy code
fun String.unless(condition) = if (condition) "" else this
Copy code
fun String.unless(condition: (String) -> Boolean) = if (condition(this)) "" else this
is nice too
l
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
Sometimes if it's part of a bigger string building system you can conditionally append too:
Copy code
buildString {
    if (cond) append(str)
}
h
i think the name of the functions are enough context given they're called alongside concatenation or other operations