SuitCase is a convenient Java library dedicated to object manipulation using
pattern matching mechanism.
If you want to manipulate object based on types in Java the dedicated design pattern is the visitor. Unfortunately even if such pattern is well known its implementation is always painful because it implies code dissemination and finally brakes incremental compilation approach.
In addition such mechanism only enables selection based on types and does not provides a simple and intuitive mechanism filtering objects using their values i.e. attributes.
For this purpose a simple pattern matching inspired by Scala extractor object has been designed.
This pattern matching offers a simple mechanism for simple object selection based on intrinsic equality. Indeed pattern matching cases can be done on the object kind and it's internal state. For instance the following sample checks if an integer is O or not.
Matcher<Integer, Boolean> isZero = Matcher.match(); isZero.caseOf(0).then(true); isZero.caseOf(Any()).then(false); isZero.match(0); // == true
Regexp, List Patterns and more ...
More information and descriptions are given in the Wiki and in particular ad-hoc case is explained with practical implementations covering matching for lists, string regular expression, XML etc.
This library is available at Sonatype OSS Repository Hosting service and can be simply used adding the following dependency to your pom project.
<dependency> <groupId>org.smallibs</groupId> <artifactId>suitcase</artifactId> <version>0.3</version> </dependency>
Other Propositions & Discussions
A review of various approaches is given in the Structural Pattern Matching in Java. It starts from the visitor and proposes alternatives with a functional programming approach.
Copyright (C)2015 D. Plaindoux.
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.