On Thursday June 18 2009, Eric Bowman wrote:
> The basic trick where a superclass has its subclass as a type
> parameter, e.g.
>
> class User extends MegaProtoUser[User]
>
> I've run into this before, I remember struggling to "get it", then
> getting it, but I can't recall the epiphany. But obviously this is a
> relatively common technique, so something to google is much
> appreciated.
The example I find helps the most to make this comprehensible is Ordered
(generically, not necessarily Scala's actual Ordered class):
What does it mean for something to be able to be ordered? It means that
if you give me two instances of such a thing, I can tell you whether
they stand in a particular order (which may be numeric but need not be;
other examples include lexicographic ordering or something defined on a
metric space like edit distance). No breathtaking insight there.
So naturally when I want to capture orderability generically, I have to
say that it establishes a relationship with other things of the same
(or compatible / conformant) type. Thus:
class Ordered[WithRespectToWhat]
Now, to define a class that conforms to Ordered, we have to
specify "ordered with respect to what?" And the usual answer is "with
respect to the same type:"
class Numeric extends Ordered[Numeric]
You might reasonably want that to be covariant:
class Ordered[+WithRespectToWhat]
But by cheating (me cheating in writing this up, that is) we find in the
ScalaDocs this note on the page for Ordered [1]:
"Note that since version 2006-07-24 this trait is no longer covariant in
a. It is important that the equals method for an instance of Ordered[A]
be consistent with the compare method. However, due to limitations
inherent in the type erasure semantics, there is no reasonable way to
provide a default implementation of equality for instances of
Ordered[A]. Therefore, if you need to be able to use equality on an
instance of Ordered[A] you must provide it yourself either when
inheiriting or instantiating."
[1] <http://www.scala-lang.org/docu/files/api/scala/Ordered.html>
> Thanks,
> Eric
Randall Schulz
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Lift" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/liftweb?hl=en
-~----------~----~----~----~------~----~------~--~---