Checking for valid entries



I am learning more and more about Kotlin every day. I have found myself facing another interesting roadblock.

Using the code below, I want to write a check that verifies if the user actually entered a number. If not, I want to go back and ask them to enter again. If they DID enter a number, I want to value to proceed into the calculateTotal function. How would I check if an entry matches the criteria? Thanks in advance.

print("Enter the total of your bill : ")
    var originalTotal: Double?
    originalTotal  = readLine()!!.toDouble()
    if(originalTotal !is Double) {
        println("You did not enter a valid entry:")

    } else {
        val taxTotal = calculateTotal(originalTotal)
        println("Your total with standard tip is: $taxTotal")



The following is what I have. It only runs the first println and then gives the following error:

Exception in thread “main” kotlin.KotlinNullPointerException
at Simplest_versionKt.main(Simplest version.kt:10)

fun main(args: Array<String>) {
    var originalTotal: Double?
    do {
        println("Please enter the total of your bill: ")
        originalTotal= readLine()!!.toDoubleOrNull()
        if(originalTotal == null){
            println("Not a valid number, try again")
    var tip = 0.15 * originalTotal
    println("Your tip is: $tip")
    var total = originalTotal + tip
    println("Your total is: $total")


What about a function that only returns if the readLine() get a not null transformation:

fun <T> readLineNotNull(transformation: (String) -> T): T =
	transformation(readLine() ?: "")?.let { return it } ?: readLineNotNull(transformation)

then use it like:

val myDouble = readLineNotNull { it.toDoubleOrNull() } // read line until a Double is entered
val notOne = readLineNotNull { if (it == "1") null else it.toDoubleOrNull() } // read line until it's diferent from "1" and is a Double


It runs fine on my machine - here’s some sample output:

Please enter the total of your bill: 
Your tip is: 15.0
Your total is: 115.0

It’s difficult to see what could be null here as originalTotal must be a number after the do/while loop ends.

I’d scrub what you have, try pasting the above code in again and see if the result is the same.