1

I have the following code:

val n = readln().toIntOrNull()
   
if (n > 3) {
   println(n)
}

I am receiving above subject error:

Operator call corresponds to a dot-qualified call 'n.compareTo(3)' which is not allowed on a nullable receiver 'n'.

However, if I write n == 3, I don't get the error. How to correct that without using try{} and catch{}?

I Would appreciate any help.

u-ways
  • 6,136
  • 5
  • 31
  • 47
Jaguar
  • 15
  • 6

1 Answers1

0

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:

u-ways
  • 6,136
  • 5
  • 31
  • 47
  • 1
    Got it. Thank you very much! I was using val n = readln().toIntOrNull() ?: "Enter Number Only" That did not work – Jaguar Mar 03 '23 at 03:49
  • You're welcome, it did not work because you converted the Int to String, so now you're no longer doing a numeric compare. If you wanted to error, then you can try: `error("Enter Number Only")`. – u-ways Mar 03 '23 at 03:55