Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

What's wrong with:

    data class Point(val x: Int, val y: Int)

    // Later on...

    if (p is Point) {
        let (x, y) = p
        // x and y are of type Int
    }
That Kotlin has, already, now?


It doesn't allow you to match on individual members of the class. For example, in future Java I should be able to do:

    if (p instanceof Point(0, 0)) {
        // handle origin
    } else if (p instance of Point(x, y)) {
        // ...
    }
and it will get even more complex with matching on nested types (e.g. `if (r instance of Rectangle(Point(0, 0), Point(1, 1))) { ... }).

This will be much nicer once it starts working with `switch` expressions too.


It's been a while since I've used Java and it seems weird to me to see instanceof used to check values instead of types. That sounds a lot like instance of being used instead of .equals(). Why not?

    if (r.equals(new Rectangle(Point(0, 0), Point(1, 1)) s) {
       s.doStuff();
    }
Are they really planning to use instanceof to check for equality?


It's not exactly the same as equality checking, as each has its own uses. You can override `equals` to reflect specific semantics. Say for example you have a non-public ID field for your Point class that is used to determine uniqueness, such that points with different IDs are not equal regardless of their x, y values (maybe not the best example, but the point holds, arguably however, that would be bad practice for records anyway).

Secondly, using equals as per the code you provided incurs at least 3 allocations (1 Rectangle and 2 Points), whereas using pattern matching there are no such allocations.

Furthermore, and probably the main point of pattern matching, is that it allows for "deconstructing" records into variables so that they can be examined individually. I can handle any Point on the x-axis at y = 0 by simply matching against `p instanceof Point(var x, 0)`, or all rectangles with their first point is the origin by matching against `r instanceof Rectangle(Point(0, 0), var p)`, it's much cleaner and clearer than writing something like:

    if (r.getFirstPoint().x() == 0 && r.getFirstPoint().y() == 0) {
        var p = r.getSecondPoint();
        // ...
    }
Not to mention once we have sealed types we can do something like:

    var area = switch(shape) {
        case Circle(var r) -> Math.PI * r * r;
        case Square(var s) -> s * s;
        case Rectangle(var l, var w) -> l * w;
        ...
    }
Pattern matching has been available in many other languages (e.g. the ML family of languages, and some JVM languages like Scala), and now Java is also gaining this feature.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: