Scala隐式参数的Groovy等价物

Ghi*_*iro 2 groovy scala implicits

是否有一些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
Run Code Online (Sandbox Code Playgroud)

更新:请参阅此处的后续问题:Groovy等效于Scala隐式参数 - 扩展

Art*_*ero 5

您可以使用具有默认参数的闭包:

doSomethingWith = { i = value -> println "Got $i" }
value = 5

doSomethingWith(6)  // Got 6
doSomethingWith()   // Got 5

value = 0
doSomethingWith()   // Got 0
Run Code Online (Sandbox Code Playgroud)

  • 这个答案很合适,但它有什么相似之处?在Groovy示例中,`value`变量和`value`默认参数值必须相同.在Scala`x`中,局部变量和`i`可以有不同的名称,并在不同的位置定义. (5认同)