0

I'm new to Kotlin and I'm error "Type mismatch: inferred type is Double? but Double was expected" on return values of the operation functions I created. The fix recommended is to assert the num2 value as non-null but I don't understand why that is?

import java.lang.NumberFormatException

fun main(args: Array<String>) {
    val num2: Double?
    val num1:Double?
    val op:String?
    var result:Double? = null

    try {
        print("Input number 1: ")
        num1 = readLine()?.toDouble()
        print("Input number 2: ")
        num2 = readLine()?.toDouble()
        print("Pick operation ( + - / *) ")
        op = readLine()

        when (op) {
            "+" -> result = addVal(num1, num2)
            "-" -> result = substractVal(num1, num2)
            "*" -> result = multiplyVal(num1, num2)
            "/" -> result = divideVal(num1, num2)
            else -> {
                print("Operator not found. Could not complete operation")
            }
        }
    } catch (e: NumberFormatException) {
        println("${e.message} is not a number")
    }

    println(result)
}

// Operation functions
fun addVal(num1: Double?, num2: Double?): Double? {
    return num1?.plus(num2)
}

fun substractVal(num1: Double?, num2: Double?): Double? {
    return num1?.minus(num2)
}

fun multiplyVal(num1: Double?, num2: Double?): Double? {
    return num1?.times(num2)
}

fun divideVal(num1: Double?, num2: Double?): Double? {
    return num1?.div(num2)
}
Cedric M.
  • 33
  • 7
  • Basically the same idea as here: [Kotlin Convert Double? to Double](https://stackoverflow.com/questions/64376040/kotlin-convert-double-to-double). Have a read in that and [Null Safety in Kotlin](https://kotlinlang.org/docs/null-safety.html) – AlexT Feb 23 '21 at 15:40
  • 1
    Use `readLine()!!` and you won't have to declare things as nullable. `readLine()` only returns null if you're using file input, so it's safe to use !! here. – Tenfour04 Feb 23 '21 at 15:58
  • @Tenfour04 There's always a risk of `readLine()` returning null, even from keyboard input — e.g. from typing Ctrl+D on an empty line, to send an end-of-file indication.  (I think the Windows equivalent is Ctrl+Z.) – gidds Feb 23 '21 at 18:42
  • Oh, good point. It's Ctrl+D on Windows. – Tenfour04 Feb 23 '21 at 18:53

0 Answers0