[英]Groovy equivalent for Scala implicit parameters
Is there some Groovy alternative to express something like the following: 是否有一些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
Update: see a followup question here: Groovy equivalent for Scala implicit parameters - extended 更新:在此处查看后续问题: 与Scala隐式参数等效的Groovy-扩展
You can use closures with a default parameter: 您可以将闭包与默认参数一起使用:
doSomethingWith = { i = value -> println "Got $i" }
value = 5
doSomethingWith(6) // Got 6
doSomethingWith() // Got 5
value = 0
doSomethingWith() // Got 0
This is how I do implicits in Groovy 这就是我在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(" ", "")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.