Live data from Hacker News

Pattern Matching for Java

cr.openjdk.java.net

51–60 of 152 posts

Re: Pattern Matching for Java

#52
How about...

    instanceOf x is? {
        Int { System.out.println("It's an Int"); }
        String { System.out.println("Hello, " + x); }
        _default { System.out.println("This type is not explicitly named here."); }
    }

And if you don't want the type, the value of any other method, function, or attribute could be checked by "is?" or whatever syntax token you want there.

Further tests could be saved for within those blocks to save complexity.

What's odd though is that in Java this particular example seems to want multi-method. Testing the type explicitly and acting on it is more akin to duck-typed language programming. You see this pattern pretty often in Perl for example. If I want to write in Perl, I typically reach for Perl.

Re: Pattern Matching for Java

#53
post #32
post #15

Earlier quoted context omitted.

How is that bad code style? That's exactly what virtual method dispatch does. The authors in the article even address this point, stating that some operations might make sense as instance methods if they are instrinsic to the type hierarchy, but others, especially ad-hoc queries, are extrinsic to the types and best expressed as pattern matching. Simply calling this "bad code style" sounds a lot like a justification f…

Enumerating and testing for type equality each derived classes in one place (i.e. manual type switch) is certainly a bad code practice in OO languages. Yes, the better way is to let virtual method dispatch mechanism decide.

Depends. It's useful when you want to have all dispatch code in one place (as opposed to it being scattered across numerous files). Doubly so if your language (like most languages) lacks multimethods. Triply so, if you need to dispatch on built-in types you can't extend, which sometimes happens in e.g. Java.

Re: Pattern Matching for Java

#54
post #13
post #5

Pattern matching is possibly one of the most under-utilized approaches that can simplify a lot of ugly/complex logic.

On the other hand it "prettifies" bad code style - branching by dynamic casts / type comparisons.

Keep in mind that it is mostly considered bad code style today (at least in Java) because the current tools we have (if-statements, instanceof checks, like the article lays out) lead to bugprone code. A better facility like pattern matching could eliminate a lot of this.

Re: Pattern Matching for Java

#55
post #19

IMO the hierarchy of need for this goes: 1 - case classes / value classes / data classes, whatever you want to call them. 2 - match-and-bind syntax ... 11? - fancy pattern matching This maybe says more about how much I pay attention to what's upstream in Java, but I found the fact that this is just a hypothetical proposal, in April of 2017, strangely shocking. I guess I figured it had to be on the docket for a future…

I think some/most of the "needed" features for Java are already available in some other JVM languages. I'm not too familiar with the JVM ecosystem but Kotlin comes to mind.

Re: Pattern Matching for Java

#56
post #30

Why the fixation on pattern matching? Don't get me wrong, I enjoy the benefit it provides, but for OO code multiple dispatch is a more elegant and idiomatic way to solve the "I don't want to implement the visitor pattern" problem. FYI, I recently found out that C# can actually do multiple dispatch https://blogs.msdn.microsoft.com/shawnhar/2011/04/05/visitor...

Multiple dispatch is sometimes more elegant, provided you can divorce the method being dispatched to from the argument classes. If you need to do it with a visitor pattern and multiple callbacks, it's much worse. If you need completeness checking, it's worse. If you've got a simple concise algorithm best expressed in a loop, it's worse. If you've got a nested structure that you want to partially destructure, it's wor…

would you be able to give me a pseudo code example of things that are easy to do with pattern matching, but not multiple dispatch? I'm intrigued, I always considered them equivalent.

Re: Pattern Matching for Java

#57
post #19

IMO the hierarchy of need for this goes: 1 - case classes / value classes / data classes, whatever you want to call them. 2 - match-and-bind syntax ... 11? - fancy pattern matching This maybe says more about how much I pay attention to what's upstream in Java, but I found the fact that this is just a hypothetical proposal, in April of 2017, strangely shocking. I guess I figured it had to be on the docket for a future…

Maybe I'm misunderstanding your comment, but aren't case classes a fundamental piece of pattern matching? Or are you rather just suggesting the importance of which kinds of pattern matching are the most important?

Re: Pattern Matching for Java

#58

Why the fixation on pattern matching? Don't get me wrong, I enjoy the benefit it provides, but for OO code multiple dispatch is a more elegant and idiomatic way to solve the "I don't want to implement the visitor pattern" problem. FYI, I recently found out that C# can actually do multiple dispatch https://blogs.msdn.microsoft.com/shawnhar/2011/04/05/visitor...

> FYI, I recently found out that C# can actually do multiple dispatch But also good to know, that it can be costly and unsafe. `dynamic` is basically using reflection at run-time, which for most cases is fine, but it's something to keep in mind. It also means that type checking is delayed until run-time instead of compile-time.

A dynamic type is probably just implemented as a tagged bit of data, surely. Which is the exact same way an algebraic datatype would be done. So I dunno why it would be any slower.

I think the safety thing is a non issue as well - what arguments could you pass in to the statically typed function that would cause the use of dynamic to bite you in the ass?

Re: Pattern Matching for Java

#59
post #39
post #37

Earlier quoted context omitted.

I mean, reading this article is basically a giant advertisement for Scala and its powerful pattern matching. functionThatReturnsAnyVal match { case i: Int if i > 2 => System.out.println("Greater than 2") case i: Int => System.out.println("Less than or equal to 2") case s: String => System.out.println("Hello, " + s) case _ => }

This still seems a terrible example just to try and avoid naming an object. Isn't the comparison to: Object o = functionThatReturnsAnyVal(); if (o instanceof Integer) { Integer i = (Integer) o; if (i > 2) { System.out.println("Greater than 2."); } else { System.out.println("Less than or equal to 2."); } } else if (o instanceof String) { String s = (String) s; System.out.println("Hello, " + s); } I get that the case s…

I think the prettier syntax actually really helps write code faster. A similar form of syntactic sugar appeared with lambda expressions. Instead of needing to explicitly subclass and write out the overriding method, you can just create an anonymous function.

It's way less code and it makes the resulting code easier to reason about. The code's intent is more elegantly conveyed.

Re: Pattern Matching for Java

#60
post #39
post #37

Earlier quoted context omitted.

I mean, reading this article is basically a giant advertisement for Scala and its powerful pattern matching. functionThatReturnsAnyVal match { case i: Int if i > 2 => System.out.println("Greater than 2") case i: Int => System.out.println("Less than or equal to 2") case s: String => System.out.println("Hello, " + s) case _ => }

This still seems a terrible example just to try and avoid naming an object. Isn't the comparison to: Object o = functionThatReturnsAnyVal(); if (o instanceof Integer) { Integer i = (Integer) o; if (i > 2) { System.out.println("Greater than 2."); } else { System.out.println("Less than or equal to 2."); } } else if (o instanceof String) { String s = (String) s; System.out.println("Hello, " + s); } I get that the case s…

In reality my function would rarely exist in the Scala world since having a weakly-typed return like that is cringeworthy to say the least. But it's better to see this in action with Scala options.

  val myOptionalVar: Option[String] = functionThatReturnsOption()

  myOptionalVar match {
    case Some(str) if str.length > 10 => System.out.println("This is a long string.")
    case Some(str) => System.out.println("This is a short string.")
    case None => System.out.println("This code would be fifteen lines of null checking in Java.")
  }
Post reply on HN