hello everyone, i am looking for a control functio...
# announcements
a
hello everyone, i am looking for a control function
elseIf
it should allow me to take another value if the predicate does return true. i implemented the following extension function:
Copy code
inline fun <T> T.elseIf(predicate: T.() -> Boolean, supplier: () -> T) : T =
        when {
            predicate() -> supplier.invoke()
            else -> this
        }
its called like
val i = "ssss".elseIf({isEmpty()}) {"other"}
which feels very clumsy. can i optimize the syntax more? or arent there already alternatives in kotlin? or maybe im just missing the easy solution?
o
val i = "ssss".takeIf { it.isEmpty() } ?: "other"
☝️ 4
or even
"ssss".takeIf(String::isEmpty) ?: "other"
☝️ 1
a
ok....that looks good
k
Copy code
val s = "ssss"
if (s.isEmpty()) "other" else s
3
a
thx..that the obvious one...but i prefer takeIf...but still think its not optimal
d
"sss".orEmpty { "other" }
k
Isn't that for converting
null
to
""
?
d
Hmm, lemme confirm.
😅 I meant
"sss".ifEmpty { "other" }
a
well these are great, but specific to string
d
I think these are only useful when they are specific. Otherwise it's harder to read.
a
well my function is not so bad, but unfortunately calling it looks strange but its generic
File("").elseIf({!exists()}, {File("other)})
otherwise olegs takeif seems the best
m
Even though I would prefer the plain `if`:
Copy code
infix fun <T> T.unless(predicate: T.() -> Boolean) = this to predicate
infix fun <T> Pair<T, T.() -> Boolean>.then(supplier: () -> T) = when {
    first.second() -> supplier()
    else -> first
}

"ssss" unless { isEmpty() } then { "other" }
😲 1
g
I often use File with
takeIf
, and it works file, also more flexible, because you part after
?:
also can be return, break etc:
Copy code
File("").takeIf(File::exists) ?: File("other")
// or 
File("").takeIf(File::exists) ?: return
// or
File("").takeIf(File::exists) ?: error("...")
1
If you very often need this pattern with alternative File, I would just write
File.ifNotExtists
extension, like
String.ifEmpty
but I would do this only if I need it multiple times, for single usage takeIf is just fine for me