Implicit Parameters
Viewing old version ee7c4c50b416ed831b51c4763d440f4d03fc922a; View Current
The Gist
In Implicit Parameters, we learn how Scala’s concept of implicits goes beyond converting values from one type to another.
My Interpretation
Suppose you have a logging class and wish to provide a way to flexibly log lists of objects. You could create an interface for turning lists into strings, giving it a type parameter. Implementers would implement a simple method to make the transformation. You would then need to provide objects of these classes to your log statements, making sure to use the correct instance, depending on the type of objects in the list.
In Scala, you can declare the “map a list to a string” parameter is implicit, which allows you to omit this object when making the call. Scala will search for a object in scope that can be used automatically.
Here, the log messages are unencumbered by the mapper objects. Note that if we had a call like
logger.logList(List(true,false,false,true))
we would get a compile error, since there is no matching object. Note that we could define a class named BooleanListLogger and send an instance of it to the logList method (however we must use a different syntax):
logger.logList(List(true,false,false,true))(new BooleanListLogger)
Note that we can’t use a form like (param1,param2) because of how the logList method is defined, we must use (param1)(param2).
My Thoughts on this Feature
I wanted to define the two implicit objects as part of the Logger class, as that seems more useful. Defining them in the calling scope seems rather useless and encouraging of repetition.
Further, the different syntax for non-curried methods and curried methods seems arbitrary; can’t the compiler figure out that if I use the standard (param1,param2) syntax, to pass param2 into the second argument?! Very odd.
Last Updated 07/31/2009 at 03:01:46 PM by davec
blog comments powered by Disqus
All Content by David Copeland is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.