是否有一些Groovy替代方法可以表达如下内容:
def doSomethingWith(implicit i:Int) = println ("Got "+i)
implicit var x = 5
doSomethingWith(6) // Got 6
doSomethingWith // Got 5
x = 0
doSomethingWith // Got 0
更新:请在此处查看后续问题:Groovy equivalent for Scala implicit parameters - extended
答案 0 :(得分:5)
您可以使用具有默认参数的闭包:
doSomethingWith = { i = value -> println "Got $i" }
value = 5
doSomethingWith(6) // Got 6
doSomethingWith() // Got 5
value = 0
doSomethingWith() // Got 0
答案 1 :(得分:0)
这就是我在Groovy中的含义
@Test
def void customString() {
println "Welcome implicits world in groovy".upperCaseNoSpace
println "Welcome implicits world in groovy".removeSpaces
}
static {
String.metaClass.getUpperCaseNoSpace = {
delegate.toUpperCase().replace(" ", "_")
}
String.metaClass.getRemoveSpaces = {
delegate.replace(" ", "")
}
}