android-studiokotlintype-mismatch

How to safely cast the result of readLine() to prevent a Type Mismatch using Kotlin


Many Kotlin tutorials I have watched / read have this line of code:

var number = Integer.valueOf(readLine())

And while it clearly worked before, it is now throwing a compiler error while using Android studio and Kotlin version 1.3.50. It indicates a type mismatch where the found is String? and the required is String.

Granted, I understand why this is happening, I get that a user could pass null or empty values in via the console and therefore it needs to have the optional null declaration, but I would like to understand how to fix the compiler error and keep similar code without changing too much.

While I can use both of these lines of code:

var number = Integer.valueOf(readLine()!!)

and

var number = Integer.valueOf(readLine() as String)

I believe those can throw different exceptions as outlined here

I know I am able to 'fix' this problem by using this code:

var number : String? = readLine();
if(number == null){
    number = "0"
}
val number2 = Integer.valueOf(number);

But it seems horribly inefficient. Is there a shorter way to do this using native Kotlin code?


Solution

  • If we simply call toInt() on the result from readLine(), we will get an exception if the value provided isn't an actual Integer. In order to avoid an exception, we can use toIntOrNull() from the Kotlin Standard Library.

    val x= readLine()?.toIntOrNull() ?: 0
    

    In this case, we read the line (as a String?) and if it is non-null, call toIntOrNull() on it. If that is non-null, we have our answer. Otherwise, we use 0 as the default.