我是一个很长时间的java用户,但是我第一次玩groovy。我试图通过使用.withCloseable(Closure)重新创建try-with-resources。
这对我有用,但是,我很好奇是否有办法消除额外的声明来执行演员表。
new MyCloseable().withCloseable { closeable ->
def myCloseable = (MyCloseable) closeable;
...
}
如果我尝试在没有显式转换的情况下调用MyCloseable方法,我会得到
No such property: MyCloseable for class: com.test.MyTest
groovy.lang.MissingPropertyException: No such property: MyCloseable for class: com.test.MyTest
答案 0 :(得分:3)
是否必要,当然您可以定义闭包参数的数据类型:
hashtag count(hashtag)
Brexit 3
EUref 2
Blair 2
poll 1
打印
def list = [1, 2, 3]
list.each { float i ->
println i
}
所以在你的情况下,它将是
1.0
2.0
3.0
答案 1 :(得分:1)
我为你准备了几个选项:
new MyCloseable().withCloseable { closeable ->
MyCloseable myCloseable = closeable
...
}
new MyCloseable().withCloseable { MyCloseable closeable ->
def myCloseable = closeable
...
}
new MyCloseable().withCloseable { closeable ->
def myCloseable = closeable as MyCloseable
...
}
试试groovier! :)