https://kotlinlang.org logo
Title
r

robin

03/06/2017, 8:03 PM
Is there any way to construct an instance that will equal any other object? This comes close:
val any = object {
    override fun equals(other: Any?) = true
}
but only works when doing
any == "Test"
, not the other way around:
"Test" == any
. Is there any way to make the latter work?
m

mfulton26

03/06/2017, 8:17 PM
robin: Not from what I can tell. Even if you could, you shouldn't. See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/equals.html.
r

robin

03/06/2017, 8:19 PM
I know these rules, I wouldn't use this on ordinary objects. I was hoping to create some sort of replacement for true pattern matching, which could work like this:
when(a to b) {
    0 to 0 -> ...
    0 to any -> ...
    any to 0 -> ...
}
m

mfulton26

03/06/2017, 8:20 PM
You can accomplish something similar using `Comparable.compareTo`:
fun main(args: Array<String>) {
    println("Test".compareTo(Anything))
    println(Anything.compareTo("Test"))
}

object Anything : Comparable<Any?> {
    override fun compareTo(other: Any?) = 0
}

fun Any?.compareTo(anything: Anything) = 0
r

robin

03/06/2017, 8:21 PM
That would work generally, but I don't think the
when
statement uses the
Comparable
interface, does it?
m

mfulton26

03/06/2017, 9:25 PM
Any reason you aren't using if statements?
if (a == 0 && b == 0) {

    } else if (a == 0) {

    } else if (b == 0) {

    }
I suppose this works with
when
to:
when {
        a == 0 && b == 0 -> ...
        a == 0 -> ...
        b == 0 -> ...
    }
Or even:
when (0) {
        a or b -> ...
        a -> ...
        b -> ...
    }
r

robin

03/06/2017, 10:06 PM
Yeah those work, but I was looking for a more concise notation, because those quickly get hard to read with longer variable names and more cases.