Scala implcit parameters on constructor
Scala's implicit conversion is a so much cool feature which allows you extends exiting libraries without changing source codes. It works like a wrapper but transparent to users.
Says I have a string representing a URL, by implicit conversion
implicit def toMyRichString(url:String) = new MyRichString(str){
def getText={
//...
}
}
to make a String richer (even richer than RichString). I can use
"http://www.scala-lang.org".getText
to retrieve the html text from Scala site.
The possibility is unlimited and the feature is almost free. It does have performance lost, but comparing to other dynamic language (such as Groovy), this is way much better.
Implicit parameter is even cooler but subtle. It kinds of allows you to provide a default value to your function parameter so you can invoke a function without specifying that parameter. The requirement is you must provide such a value (of same type) in the context of that invoking.
Implicit parameter can also be used on constructor. This gives me such an idea that this could be used in some scenario of dependency injection or auto-wiring. The first case I think out is about log. So here is an example:
class Log(val name:String){
def log(msg:String){
println("["+name+"] " + msg)
}
}
implicit def anyRefToLogger(t:AnyRef) = new Log(t.getClass.getName)
class Test(val arg:String)(implicit log: AnyRef=>Log){
log.log("Hello " + arg)
}
new Test("Implicit Cool")
Which may seems trivial but quite interesting to me.
0 comments:
Post a Comment