Hi guys, Today I noticed weird problem on equals(...
# announcements
g
Hi guys, Today I noticed weird problem on equals() function it basically; class Event(val endTime: Long?){ fun isGoingEvent() = ((endTime == null) || endTime?.equals(0)) } Event(0L).isGoingEvent() ----> returns false if I change isGoingEvent() implementation with: fun isGoingEvent() = ((endTime == null) || endTime?.equals(0L)) it works as expected. It make sense because it compares Long with Long but I confused how should I compare values?
m
Use
endTime == 0
. It will give you a compile error if the types don't match. You usually don't use
equals
directly in Kotlin.
r
Copy code
endTime.let { it == null || it == 0 }
Wait
endTime
isn’t a
var
so this should work
Copy code
endTime == null || endTime == 0
👆 1
g
but endTime Long so we can't compare like == 0(compile error) my confusion is on equals side which is accepts any type (endTime?.equals(0)) , I would expect it should check type because both of them Number and it should cast correct type and call equals function
Sample implementation public open operator fun equals(other: Any?): Boolean if (other is Number) { this.equals(other.toLong()) }
m
Yes, when you are comparing with a Long, you have to do
endTime == 0L
. Kotlin does not perform any conversions like Java do.
The
equals
function takes an
Any
as parameter, so it just doesn't check types at all.
Integer.valueOf(someInt).equals(someLong)
will always return false in Java. It's better to have it give a compile error.
r
Yes,
endTime == 0
would always be false so why allow it anyway? You need
Copy code
endTime == null || endTime == 0L