Skip to content

Pattern Matching Java Objects

frenchy64 edited this page Aug 26, 2011 · 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=> (match [(java.util.Date. 2010 10 1 12 30)]
                    [{:year 2009 :month a}] a
                    [{:year (2010 | 2011) :month b}] b
                    :else :wrong)
10
Clone this wiki locally