Is there any way to construct an instance that wil...
# announcements
r
Is there any way to construct an instance that will equal any other object? This comes close:
Copy code
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
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
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:
Copy code
when(a to b) {
    0 to 0 -> ...
    0 to any -> ...
    any to 0 -> ...
}
m
You can accomplish something similar using `Comparable.compareTo`:
Copy code
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
That would work generally, but I don't think the
when
statement uses the
Comparable
interface, does it?
m
Any reason you aren't using if statements?
Copy code
if (a == 0 && b == 0) {

    } else if (a == 0) {

    } else if (b == 0) {

    }
I suppose this works with
when
to:
Copy code
when {
        a == 0 && b == 0 -> ...
        a == 0 -> ...
        b == 0 -> ...
    }
Or even:
Copy code
when (0) {
        a or b -> ...
        a -> ...
        b -> ...
    }
r
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.