I am new to Kotlin. I am following along a tutorial where the GUI portion involves this code snippet:
sampleList.addMouseListener(object: MouseAdapter() {
override fun mouseClicked(mouseEvent: MouseEvent?) {
if (mouseEvent?.clickCount == 2) {
launchSelectedSample()
}
}
})
mouseEvent
is obviously something nullable. I am used to, in previous coding experience, changing a line like mouseEvent?.clickCount == 2
to mouseEvent?.clickCount > 1
(or maybe >=2
), to ensure there is no corner case where the clicks happen so quickly that it jumps from 1 to 3, or something similar.
So, I switched this code to:
sampleList.addMouseListener(object: MouseAdapter() {
override fun mouseClicked(mouseEvent: MouseEvent?) {
if (mouseEvent?.clickCount >= 2) {
launchSelectedSample()
}
}
})
Upon making the switch (changing ==2
to >=2
), I received the following error from IntelliJ:
Operator call corresponds to a dot-qualified call 'mouseEvent?.clickCount.compareTo(2)' which is not allowed on a nullable receiver 'mouseEvent?.clickCount'.
This raised 2 questions for me:
- Why does
==2
work fine, but>=2
does not work? (I tried>1
, which gave the same error as>=2
.) - What is the right way to handle a corner case where, what I really want is anything greater than 1?
I like the idea of ensuring null
s don't screw things up during runtime, but I kinda wish if Kotlin just got rid of null
values altogether and did something like Rust or Haskell. (I do like what I've seen of Kotlin so far, though.)