Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - "If readLine() is null or empty assign default value, else parse readLine()"

Tags:

kotlin

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!

like image 742
Tim Gonzales Avatar asked Jan 29 '23 10:01

Tim Gonzales


2 Answers

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.

like image 84
zsmb13 Avatar answered Jan 31 '23 09:01

zsmb13


Using the elvis operator and null-safe calls

fun main(args: Array<String>) {
    val parsed = readLine()?.toDouble() ?: 0.0
}
  • Using ?. calls the method only if the value is not null, otherwise it just passes null along.
  • Using ?: means that the value on the left is returned if it is not null, otherwise the value on the right is returned
like image 36
jrtapsell Avatar answered Jan 31 '23 10:01

jrtapsell