What is a better way than `val port = property.get...
# announcements
n
What is a better way than
val port = property.getProperty("notification.port").orEmpty().let { if (it.isNotBlank()) it else "7100"}
? Is there something like ``val port = firstContent(property.getProperty("notification.port"), "7100")` ?
i
Not sure what is property, but perhaps
property.getProperty("notification.port")?.ifBlank { null } ?: "7100"
?
n
thx.
getProperty
is a Java function which returns a
String?
. I was looking for something like
String?.isNotNullOrBlankOrElse(def: String): String
(obviously with a better name).
with
fun String?.contentOrElse(def: String) = if (isNullOrBlank()) def else this
I could write
val port = property.getProperty("notification.port").contentOrElse("7100")
. But such a function does not exists in the Kotlin stdlib, does it?
s
Maybe
property.getProperty("notification.port")?.takeIf { it.isNotBlank() } ?: "7100"
?
👆 1
👍 1
n
I like that better than the
ifBlank { null }
approach, thx.
👍 1
s
Could do function ref too:
?.takeIf(String::isNotBlank)
n
might also throw in a
?.toIntOrNull()
call in there
n
yes to
?.takeIf(String::IsNotBlank)
. This looks pretty readable and this
takeIf
approach is more general than my
contentOrElse
because I could do e.g.
?.takeIf { it.length > 3 } ?: "longEnough"
🚀 1
@nanodeath: yes is this case, but I have a dozen or so in my code (host, path, query, ...) and most are actually
String
and not
Int
👍 1
h
most are actually
String
and not
Int
hi, my name is javascript, and these are the same thing
😆 1
n
welcome, javascript! Once you grow up you will hopefully learn from and correct your life choices!