Andreas Unterweger
09/27/2019, 1:01 PMelseIf
it should allow me to take another value if the predicate does return true. i implemented the following extension function:
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?Oleg Yukhnevich
09/27/2019, 1:04 PMval i = "ssss".takeIf { it.isEmpty() } ?: "other"
"ssss".takeIf(String::isEmpty) ?: "other"
Andreas Unterweger
09/27/2019, 1:07 PMkarelpeeters
09/27/2019, 1:08 PMval s = "ssss"
if (s.isEmpty()) "other" else s
Andreas Unterweger
09/27/2019, 1:09 PMDominaezzz
09/27/2019, 1:12 PM"sss".orEmpty { "other" }
karelpeeters
09/27/2019, 1:13 PMnull
to ""
?Dominaezzz
09/27/2019, 1:13 PM"sss".ifEmpty { "other" }
Andreas Unterweger
09/27/2019, 1:16 PMDominaezzz
09/27/2019, 1:27 PMAndreas Unterweger
09/27/2019, 1:34 PMFile("").elseIf({!exists()}, {File("other)})
otherwise olegs takeif seems the bestmolikuner
09/27/2019, 4:13 PMinfix 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" }
gildor
09/30/2019, 2:29 AMtakeIf
, and it works file, also more flexible, because you part after ?:
also can be return, break etc:
File("").takeIf(File::exists) ?: File("other")
// or
File("").takeIf(File::exists) ?: return
// or
File("").takeIf(File::exists) ?: error("...")
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