Question

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

Was it helpful?

Solution

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

OTHER TIPS

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(" ", "")
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top