Home > Back-end >  Kotlin 2 Errors: error: unexpected tokens (use ';' to separate expressions on the same lin
Kotlin 2 Errors: error: unexpected tokens (use ';' to separate expressions on the same lin

Time:09-15

I am trying the LeetCode 2-Sum problem and I am trying the following code:

var h = HashMap<Int, Int>()
var a = IntArray(2)
...few lines down...
a[1] = h.get(nums[i])

And I get an error that says error: smart cast to 'Int' is impossible, because 'h.get(nums[i])' is a complex expression

And I try to remedy this by modifying the first line of the code to be:

var h = HashMap<Int, Int>()?

And then I get the following error: error: unexpected tokens (use ';' to separate expressions on the same line)

What am I doing wrong? Why is the ? not working? Thank you!

CodePudding user response:

Map.get returns a nullable type (it returns null if the key is not found).

If you want to assign the result to a non-nullable left hand side (like a[1]), you need to do one of these things:

A) Provide a default value to use if the key is absent:

a[1] = h.get(nums[i]) ?: 0

// or

a[1] = h.getOrDefault(nums[i], 0)

B) Throw an exception if the key is not present:

a[1] = h.get(nums[i]) ?: throw IllegalStateException()

C) Tell the compiler you are absolutely sure the value is not null, using the !! operator (this is dangerous, and generally discouraged since it can lead to NullPointerExceptions):

a[1] = h.get(nums[i])!!

Alternatively, if you actually want to assign null to a[1], you'll need to declare the array differently:

var a = arrayOfNulls<Int>(2)

As for this...

var h = HashMap<Int, Int>()?

The ? is in the wrong place. If your intent were to declare a nullable variable that refers to a mutable map, you could write:

var h: MutableMap<Int, Int>? = HashMap<Int, Int>()

... but that probably won't help solve your problem :-)

  • Related