Skip to content

Pattern Matching Java Objects

Josh Freckleton edited this page Jun 23, 2016 · 6 revisions

Match makes it simple to pattern match any Java object.

Simply extend a type to match.core/IMatchLookup and implement val-at.

(extend-type java.util.Date
  IMatchLookup
  (val-at [this k not-found]
    (case k
      :year    (.getYear this)
      :month   (.getMonth this)
      :date    (.getDate this)
      :hours   (.getHours this)
      :minutes (.getMinutes this)
      not-found)))

We can now pattern match the Java Object as if it was any other map.

match.perf=> (matchm [(java.util.Date. 2010 10 1 12 30)]
                     [{:year 2009 :month a}] a
                     [{:year (2010 | 2011) :month b}] b
                     :else :wrong)
10

Matching Java Beans

clojure.core/bean makes pattern matching Java Beans incredibly easy.

(extend-type java.awt.Color
  IMatchLookup
  (val-at [this k not-found]
    (get (bean this) k not-found)))
match.core=> (match [java.awt.Color/black]
                    [{:red red :green green :blue blue}] [red green blue]
                    :else :error)
[0 0 0]
match.core=> (match [java.awt.Color/blue]
                    [{:red red :green green :blue blue}] [red green blue]
                    :else :error)
[0 0 255]
Clone this wiki locally