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.20101011230)]
[{:year2009: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)
[000]
match.core=> (match [java.awt.Color/blue]
[{:red red :green green :blue blue}] [red green blue]
:else:error)
[00255]

Clone this wiki locally