How to correct that without using try{} and catch{}?
You can avoid that by making your call to n
safe.
// If n is null, then you can return 0!
val n = readln().toIntOrNull() ?: 0
if (n > 3) {
println(n)
}
Now, you no longer need to worry about n
being null
.
You can also handle it as an error:
val n = readln().toIntOrNull() ?: error("Not a Number")
Alas, it all depends on your requirements.
This is known as an "Elvis operator":
When you have a nullable reference, b, you can say "if b is not null, use it, otherwise use some non-null value":
val l: Int = if (b != null) b.length else -1
Instead of writing the complete if expression, you can also express this with the Elvis operator ?::
val l = b?.length ?: -1
If the expression to the left of ?: is not null, the Elvis operator returns it, otherwise it returns the expression to the right. Note that the expression on the right-hand side is evaluated only if the left-hand side is null.
To learn more about safe calls, see: