Wednesday, November 18, 2015

Convert Java snippets to Xtend with Ctrl-Shift-V

Xtend is a dialect of Java which compiles into Java source code. The Xtend-integration in the Eclipse IDE allows developers to work simultaneously with Java and Xtend. As the syntax of both is similar, converting from Java to Xtend is not too hard, but it usually needs manual adjustments. Using the neat shortcut Ctrl-Shift-V (Ctrl+Shift+V/Cmd-Shift-V/Cmd+Shift+V) to paste Java code into Xtend files substantially reduces the manual editing. It helps to quickly get compilable Xtend code. Here are some examples of the automatic conversions.

Java type access:
EcoreUtil2.getContainerOfType(context, Model.class);
Pasted into an Xtend file:
EcoreUtil2.getContainerOfType(context, Model) 
The converter used the simpler Xtend syntax for accessing the type of Model and omitted the semicolon.

Java field with visibility:
private static final Logger logger = Logger.getLogger(
CompositeEValidator.class);
Converted to Xtend:
static final Logger logger = Logger.getLogger(
CompositeEValidator)
The default visibility for fields is private so the converter omitted it. Again, the short Xtend type access syntax was used.

Java name that is an Xtend keyword:
private String val;
Converted to Xtend:
String ^val
The Xtend keyword was automatically escaped.

Variable and cast in Java:
Model model = (Model) object;
Converted to Xtend:
var Model model = object as Model
The var/val keywords were added for mutable/final local variables and the Xtend type cast syntax was used (by the way, the type declaration of Model could be omitted due to Xtend's type inference).

Method in Java:
public void foo() { //...
Converted to Xtend:
def void foo() { //...
The default visibility for methods is public so it was omitted and the def keyword for method definitions was added.

Method overriding in Java:
public String toString() {
Converted to Xtend:
override String toString() {
As Xtend explicitly states overrides, the keyword was added (instead of def). Again, the visibility was omitted.