• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pattern Matching

 
Will Myers
Ranch Hand
Posts: 375
Java jQuery Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does Java 8 include pattern matching?
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do you mean, exactly? Java has long included an API for regular expressions, which can be used for pattern matching.
 
Tim Cooke
Sheriff
Pie
Posts: 2885
121
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think he means pattern matching as is common in functional languages. Scala for example:
 
Jaikiran Pai
Marshal
Pie
Posts: 10444
227
IntelliJ IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Haven't used Scala. Out of curiosity, what is that code example meant to do? To me it looks like equivalent to a switch case in Java:


Although, I don't see how that relates to pattern matching.
 
Tim Cooke
Sheriff
Pie
Posts: 2885
121
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is equivalent to a switch statement in Java but a good deal more flexible. Your example was close but you didn't include the default option

The example looks a bit trivial when matching with String but it becomes more powerful when you start matching on more complex types such as a List:

Or some custom type:
 
Piet Souris
Ranch Hand
Posts: 1152
19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the Scala course at Coursera I wrote the following code, to see if I got
everything correct:



Greetz,
Piet
 
Richard Reese
author
Ranch Hand
Posts: 84
5
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Will,

The first thing that came to my head was how lambda expressions are “matched” with a functional interface. While this is probably not exactly what you are asking about, it is an interesting and powerful feature of Java 8. Also, the PathMatcher interface came to mind. This was added in Java 1.7 but I do include an example of how it can be used with lambda expressions in the book.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic