I was reading through some older Scala posts to better understand type classes, and I ran across this one that seemed quite useful, but the example seems to have gotten stale.
Can someone help me figure out the correct way to do what Phillipe intended ? Here is the code
trait Default[T] { def value : T }
implicit object DefaultInt extends Default[Int] {
def value = 42
}
implicit def listsHaveDefault[T : Default] = new Default[List[T]] {
def value = implicitly[Default[T]].value :: Nil
}
default[List[List[Int]]]
When copy/pasted and run in REPL, i get this>
scala> default[List[List[Int]]]
<console>:18: error: not found: value default
default[List[List[Int]]]
^
Thanks to Jorg for his answer, which, in conjunction with this blog post helped me figure out what is going on here. Hopefully my additional answer will help others who have been confused by this.
My mental picture of type classes is that they are a means by which an author of a library would imbue his/her library with the desireable trait of retroactive extensibility.
On the other hand, there is yet another technique for ad hoc polymorphism: implicits with wrapper classes. You would use this latter technique when you are the consumer of a library which has some type which is missing methods that you find useful.
I am going to try to extend Phillipe's example a bit to illustrate my understanding of how type classes could be used by a library designer. I am not that experienced with Scala... so if anyone notices something that is not correct in my understanding please do correct me ! ;^)
Given the above code, if I can create a message for the type List[List[Int]], or for Int's
And I get this result:
If I want to override the default implicit value for a given type, I can do so like this:
And I get this result:
This doesn't have anything to do with the Scala version. If you read @Philippe's answer, you will notice that the
default
method simply isn't defined anywhere. That will not work in any Scala version.It should look something like this: