Contenu connexe Similaire à Introduction Xtend (20) Introduction Xtend6. Hello Closure
import java.util.List
import static extension java.util.Collections.*
class HelloClosure {
def static void main(String[] _) {
println(positiveOnly(newArrayList(1, 5, 2, -10, 4)))
}
def static positiveOnly(List<Integer> values) {
values.filter [it > 0]
}
}
13. Xtendの開発環境
● Eclipse + Xtend (☆Marketplace)
● 1. Javaプロジェクトを普通に作成
● 2. Xtend Classを作る
● 3. Quick Fixでライブラリを導入
● 4. あとはXtendクラスを書くだけ
● 5. 自動的にJavaソースに変換される
※ Mavenでもビルドできます
19. 演算子オーバロード
val apples = newArrayList(new Apple())
val oranges = newArrayList(new Orange())
val fruits = apples + oranges
※ 演算子の意味を多重定義できる
20. 演算子の種類(1)
e1 += e2 e1.operator_add(e2)
e1 || e2 e1.operator_or(e2)
e1 && e2 e1.operator_and(e2)
e1 == e2 e1.operator_equals(e2)
e1 != e2 e1.operator_notEquals(e2)
e1 < e2 e1.operator_lessThan(e2)
e1 > e2 e1.operator_greaterThan(e2)
e1 <= e2 e1.operator_lessEqualsThan(e2)
e1 >= e2 e1.operator_greaterEqualsThan(e2)
e1 -> e2 e1.operator_mappedTo(e2)
21. 演算子の種類(2)
e1 .. e2 e1.operator_upTo(e2)
e1 + e2 e1.operator_plus(e2)
e1 - e2 e1.operator_minus(e2)
e1 * e2 e1.operator_multiply(e2)
e1 / e2 e1.operator_divide(e2)
e1 % e2 e1.operator_modulo(e2)
e1 ** e2 e1.operator_power(e2)
! e1 e1.operator_not()
- e1 e1.operator_minus()
22. すべてが「式」
val data = if (file.exists) {
fileContentsToString(file)
} else {
'has no data'
}
※ 文じゃないから評価結果が値になる
※ caseやtry~catchも式です
23. 拡張メソッド~ローカル拡張
class Printer {
def void print(Person person) {
println(person.fullName)
}
def getFullName(Person p) {
p.firstName + " " + p.lastName
}
}
クラスにメソッドを外部から追加する
イメージで呼び出せるようになる
24. 拡張メソッド~Inject
class Printer {
@Inject extension PersonExtension
def print(Person person) {
println( person.fullName )
}
}
※ 外部定義された拡張をDIで適用する
28. クロージャ(3)~簡略化
people.filter[ Person p | "Hans" == p.name ]
people.filter[ p | "Hans" == p.name ]
people.filter[ "Hans" == it.name ]
people.filter[ "Hans" == name ]
※ 型推論や暗黙itパラメータで簡略化
29. クロージャ(4)~Builder DSL
html [
head [
title [$("XML encoding with Xtend")]
]
body [
h1 [$("XML encoding with Xtend")]
p [$("this dsl can be used as alternative to XML")]
※ BuilderなどのDSLとしても有効
30. テンプレート式
val fullName = '''Name: «p.firstName» «p.lastName»'''
def getFullName(Person p) '''
Fist name: «p.firstName»
Last name: «p.lastName»
'''
※ テンプレート文字列を簡単に作れる
※ IF/FORなどの制御構造も埋め込める
31. Switch式
val Shape shape = ...
val desc = switch (shape) {
Rectangle case shape.width == shape.height :
"Square ("+shape.width+")"
Rectangle :
"Rectangle ("+shape.width+" x "+shape.height+")"
Circle :
"Circle ("+shape.diameter+")"
default :
"Don't know"
}
※ 型ガードと条件検査を同時にできる
32. マルチプル・ディスパッチ
def example() {
val Shape s = new Rectangle()
println(s.label)
}
def dispatch label(Shape s) {
"some shape"
}
def dispatch label(Rectangle r) { ←
"a rectangle"
}
※ 実行時の型でメソッドが選択される