Search code examples
scalagroovyimplicits

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


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