Tobias Suchalla
06/01/2023, 1:27 PMTobias Suchalla
06/01/2023, 1:33 PMfun main() {
println(Status.Good.equals(Status(1))) // 1
println(Status.Good == Status.Good) // 2
println(Status.Good == Status(1)) // 3
println(Status(1) == Status(1)) // 4
println(Status.Good == Status.Bad) // 5
println(Status.Good == Status(2)) // 6
println(Status(1) == Status(2)) // 7
}
sealed class Status(open val code: Int, val name: String?) {
override fun equals(other: Any?) = (other as? Status)?.code == code
object Good : Status(1, "Good")
object Bad : Status(2, "Bad")
object Ugly : Status(2, "Ugly")
data class Arbitrary(override val code: Int) : Status(code, null)
companion object {
operator fun invoke(code: Int) = Arbitrary(code)
}
}
But comparisons 3, 5 and 6 fail to compile: "Operator '==' cannot be applied to ..."
However, comparison 1 passes, and "Go To: Declaration" on the equal signs take me to the same override fun equals(...)
of the sealed class.
I thought that a == b
is just a shortcut for a.equals(b)
. Am I wrong?CLOVIS
06/01/2023, 1:48 PMmkrussel
06/01/2023, 1:50 PMCLOVIS
06/01/2023, 1:51 PMCLOVIS
06/01/2023, 1:52 PMCLOVIS
06/01/2023, 1:53 PMWout Werkman
06/01/2023, 2:02 PMSelf
types).
I don't know in which use case this makes sense. But in the rare use case that you would ever need such comparison, I think it's not that far fetched to use .equals
mkrussel
06/01/2023, 2:09 PM==
. Just that == null
is handled.Ruckus
06/01/2023, 5:42 PMinvoke
like so:
operator fun invoke(code: Int): Status = Arbitrary(code)
3 and 6 will now compile, but not 5ephemient
06/01/2023, 7:47 PMephemient
06/01/2023, 7:49 PM> Kotlin checks the applicability of value equality operators at compile-time and may reject certain combinations of types forandA
. Specifically, it uses the following basic principle.B
>
> If type ofand type ofA
are definitely distinct and not related by subtyping,B
is an invalid expression and should result in a compile-time error.A == B
>
> Informally: this principle means “no two objects unrelated by subtyping can ever be considered equal by `==`”.
ephemient
06/01/2023, 7:49 PM.equals()
function, only the ==
operatorTobias Suchalla
06/02/2023, 6:16 AM