I'm a beginner to Kotlin and am loving it so far. I'm curious if Kotlin has a quick and simple solution to checking user input/strings for emptiness. I'd like the funtionality of the following:
"If readLine() is null or empty assign default value, else parse readLine()"
And so far, what I've come up with is this:
var inp = readLine()
val double = if(inp.isNullOrEmpty()) 0.0 else inp.toDouble()
Is this the best it can be? I'd prefer to not store the original user input string if possible. Thanks for the help!
You can use toDoubleOrNull
here:
val double: Double = readLine()?.toDoubleOrNull() ?: 0
If readLine()
returns null
, then the readLine()?.toDoubleOrNull()
expression will also return null
, and you'll fall back on the default value.
If readLine()
returns a non-null value, toDoubleOrNull
will attempt to parse it, and if it fails (for example, for an empty string), it will return null
, making you fall back to the default once again.
fun main(args: Array<String>) {
val parsed = readLine()?.toDouble() ?: 0.0
}
?.
calls the method only if the value is not null, otherwise it just passes null along.?:
means that the value on the left is returned if it is not null, otherwise the value on the right is returnedIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With