简体   繁体   中英

Groovy equivalent for Scala implicit parameters

Is there some Groovy alternative to express something like the following:

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

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

@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(" ", "")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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