Suppose a class defines an implicit function that converts an integer to a String:
class Dollar() {
implicit def currency(num: Int): String = "$" + num.toString
def apply(body: => Unit) {
body
}
}
and we also have a function that prints a number transformed by the implicit function:
def printAmount(num: Int)(implicit currency: Int => String) {
println(currency(num))
}
then we can call the method printAmount() in the constructor of the class Dollar:
val dollar = new Dollar {
printAmount(32) // prints "$32"
}
However, if we want to provide the implicit function for a code block, a compilation error occurs because the implicit value does not applied:
dollar {
printAmount(14) // Error: No implicit view available from Int => String
}
As I know, Groovy has a keyword use for the case like this. Is there any way to provide implicit functions for a certain code block in Scala?
You can change dollar such that it takes a function from a conversion function to
Unit.Then you can use dollar like this: