#10 Xtend Control Flow
Xtend comes with two new cool control flow features: dispatch and switch. Here I show how to use them to improve the coding.
- Download:
- source code Project Files in Zip (10.6 KB)
- mp4 Full Size H.264 Video (30.4 MB)
- m4v Smaller H.264 Video (17.5 MB)
- webm Full Size VP8 Video (18 MB)
- ogv Full Size Theora Video (32.3 MB)
Xtend Documentation:
- Dispatch: http://www.eclipse.org/xtend/documentation.html#polymorphicDispatch
- Switch: http://www.eclipse.org/xtend/documentation.html#switchExpression
Dispatch implementation:
xtend
class PrettyPrinterXtend1 {
public static val DecimalFormat INT_FORMAT = new DecimalFormat("00");
def public static dispatch String prettyPrint(Integer intValue) {
return "Integer: " + INT_FORMAT.format(intValue);
}
def public static dispatch String prettyPrint(Rectangle it) {
if (width == height) {
return "Square with side=" + width;
}
"Rect with width=" + width + " and height=" + height;
}
def public static dispatch String prettyPrint(Void object) {
"<null>"
}
def public static dispatch String prettyPrint(Object object) {
"Object: " + object;
}
}
class PrettyPrinterXtend1 { public static val DecimalFormat INT_FORMAT = new DecimalFormat("00"); def public static dispatch String prettyPrint(Integer intValue) { return "Integer: " + INT_FORMAT.format(intValue); } def public static dispatch String prettyPrint(Rectangle it) { if (width == height) { return "Square with side=" + width; } "Rect with width=" + width + " and height=" + height; } def public static dispatch String prettyPrint(Void object) { "<null>" } def public static dispatch String prettyPrint(Object object) { "Object: " + object; } }
Switch implementation:
xtend
class PrettyPrinterXtend2 {
public static val DecimalFormat INT_FORMAT = new DecimalFormat("00");
def public static String prettyPrint(Object object) {
switch (object) {
Integer:
"Integer: " + INT_FORMAT.format(object)
Rectangle case object.width == object.height:
"Square with side=" + object.width
Rectangle:
"Rect with width=" + object.width + " and height=" + object.height
case null:
"<null>"
default:
"Object: " + object
}
}
}
class PrettyPrinterXtend2 { public static val DecimalFormat INT_FORMAT = new DecimalFormat("00"); def public static String prettyPrint(Object object) { switch (object) { Integer: "Integer: " + INT_FORMAT.format(object) Rectangle case object.width == object.height: "Square with side=" + object.width Rectangle: "Rect with width=" + object.width + " and height=" + object.height case null: "<null>" default: "Object: " + object } } }

