Reputation: 520
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
Upvotes: 2
Views: 515
Reputation: 13471
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(" ", "")
}
}
Upvotes: 0
Reputation: 13120
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
Upvotes: 5