繁体   English   中英

与Scala隐式参数等效的Groovy

[英]Groovy equivalent for Scala implicit parameters

是否有一些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

更新:在此处查看后续问题: 与Scala隐式参数等效的Groovy-扩展

您可以将闭包与默认参数一起使用:

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

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

value = 0
doSomethingWith()   // Got 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(" ", "")
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM