Minimal framework in Scala for collections with inheriting return type

Posted by Rex Kerr on Stack Overflow See other posts from Stack Overflow or by Rex Kerr
Published on 2010-06-09T15:46:42Z Indexed on 2010/06/09 17:32 UTC
Read the original article Hit count: 143

Suppose one wants to build a novel generic class, Novel[A]. This class will contain lots of useful methods--perhaps it is a type of collection--and therefore you want to subclass it. But you want the methods to return the type of the subclass, not the original type. In Scala 2.8, what is the minimal amount of work one has to do so that methods of that class will return the relevant subclass, not the original? For example,

class Novel[A] /* What goes here? */ {
  /* Must you have stuff here? */
  def reverse/* What goes here instead of :Novel[A]? */ = //...
  def revrev/*?*/ = reverse.reverse
}
class ShortStory[A] extends Novel[A] /* What goes here? */ {
  override def reverse: /*?*/ = //...
}
val ss = new ShortStory[String]
val ss2 = ss.revrev  // Type had better be ShortStory[String], not Novel[String]

Does this minimal amount change if you want Novel to be covariant?

(The 2.8 collections do this among other things, but they also play with return types in more fancy (and useful) ways--the question is how little framework one can get away with if one only wants this subtypes-always-return-subtypes feature.)

© Stack Overflow or respective owner

Related posts about scala

Related posts about collections