Last active
May 5, 2018 13:11
-
-
Save nobeans/dd70e2cfecff7fcb5ae6945f13c985cb to your computer and use it in GitHub Desktop.
Groovy 3.0.0から改善されるシンタックス互換性
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Groovy 3.0.0からラムダ記法が使えます。 | |
//def twice = (int num) -> { num * 2 } | |
//def twice = (num) -> { num * 2 } | |
def twice = num -> num * 2 | |
twice(100) | |
assert twice instanceof Closure | |
def hoge = () -> "HOGE" | |
assert hoge() == "HOGE" | |
// Javaと同じくカンマ区切りで複数変数使えます。 | |
for (int i = 0, j = 0; i < 10; i++, j++) { | |
print "$j" | |
} | |
println '' | |
// Javaと同じ配列の初期化記法が使えます。 | |
def ints = new int[]{1, 2, 3} | |
assert ints instanceof int[] | |
//int[] ints2 = {1, 2, 3} // これはNG | |
int[] ints2 = [1, 2, 3] // なお、3以前でもこう書ける | |
assert ints2 instanceof int[] | |
// do-whileが使えます。 | |
int i = 0 | |
do { | |
i++ | |
} while (i < 5) | |
assert i == 5 | |
// メソッド参照が使えます。 | |
def upcase = String::toUpperCase | |
assert upcase("hoge") == "HOGE" | |
class MyClass { | |
static upcase(String it) { | |
it.toUpperCase() | |
} | |
} | |
def myUpcase = MyClass::upcase | |
assert myUpcase("hoge") == "HOGE" | |
// try-with-resourcesが使えます。 | |
try (def ins = new ByteArrayInputStream('hoge'.bytes)) { | |
assert ins.text == 'hoge' | |
} | |
// ブロックとして機能するだけの波括弧が使えるようになってる?? | |
// 3以前だと単なるクロージャ記法なのかブロックなのか曖昧なのでエラーになっていた。 | |
{ | |
def str = "hello" | |
println str | |
} | |
//println str //=> MissingPropertyException | |
println "done." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment