2

是否有一些 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 等效于 Scala 隐式参数 - 扩展

4

2 回答 2

5

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

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

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

value = 0
doSomethingWith()   // Got 0
于 2012-11-14T12:09:00.217 回答
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(" ", "")
    }
}
于 2016-10-16T10:06:23.860 回答