Summary
In a recent pair of articles, Luis Diego Fallas explains how to create a refactoring for Java code in the Eclipse IDE, and how to implement that refactoring using the Scala language. The article highlights how Scala can be used to effectively match a Java syntax tree.
Advertisement
Scala, the functional, object-oriented language that targets the JVM, has been receiving increasing attention [for an introduction to Scala, see the Artima article, First Steps to Scala by Bill Venners, Martin Odersky, and Lex Spoon].
Much of that interest is fueled by developers looking for a language more capable than Java, but one that still can use Java APIs and can be compiled to Java bytecode.
Pattern matching is one of Scala's strengths, and that capability comes in handy when needing to match, for example, the abstract syntax tree produced by a languageāeven when that language is Java. Matching and manipulating the AST is especially useful in the course of refactoring code.
In a pair of articles, Creating Java refactorings with Scala and Eclipse LTK, Luis Diego Fallas shows how to write refactorings for Java code with the Eclipse Language Tookit and Scala. Fallas provides a complete tutorial of a simple refactoring, including example Scala code.
The purpose of this post is to show that Scala can be used to work with existing/complex Java APIs... The refactoring that will be implemented is called "Invert IF statement blocks", the purpose of this refactoring is to swap the THEN and ELSE sections of an IF statement preserving its behavior.
In order to propagate negation several scenarios must be considered. For example if the original expression is (x == 1) the desired resulting expression must be (x != 1) , also if the condition is (x == 1) && (y == 4) then it can be transformed to (x != 1) || (y != 4). Inspired by the arithmetic simplification examples presented in Matching Objects With Patterns [a paper by Burak Emir, Martin Odersky, and John Williams], this was implemented using Scala extractors.
More information on Scala's pattern matching capabilities is available from the Scala language home page.
What do you think of using Scala for writing refactorings or other metaprogramming tasks?