How to specify that a return type of a method is a subtype of the return type of the superclass method

26 views
Skip to first unread message

Ken McDonald

unread,
Jun 1, 2012, 6:44:22 PM6/1/12
to scala...@googlegroups.com
It's been a while since I've used Scala, and am wondering if I am making things too difficult. Here's my little bit of code:

abstract class Datum(val model: Model) {
   protected def copy(model: Model): [T <: Datum];
}

class Datum1(val model: Model)
  def copy(model: Model): Datum1 = new Datum1(model)
}

The idea is that there will be many variants of DatumN, each a subtype of Datum, and each will have a "copy" method that returns an object of type DatumN. I want to be able to specify in Datum.copy that all subclasses of Datum have a copy method that returns a subtype of Datum. However, the above fails to parse at [T <: Datum]. Suggestions?

Thanks,
Ken

Derek Williams

unread,
Jun 1, 2012, 7:00:56 PM6/1/12
to Ken McDonald, scala...@googlegroups.com

Just 'Datum' should work. Subclasses can refine the type.

Ken McDonald

unread,
Jun 7, 2012, 5:44:51 PM6/7/12
to scala...@googlegroups.com, Ken McDonald
Yep, just a case me making my life overly complex. Thanks.

Ken

Josh Suereth

unread,
Jun 7, 2012, 9:14:55 PM6/7/12
to Ken McDonald, scala...@googlegroups.com
OR WAS IT?

The example you have was simple enough, don't do anything crazy.  However, when caking or virtual classing, try this out:

trait Foo {
  type T  <: BaseT
  trait BaseT { ..}
  def foo: T
}

object Bar extends Foo {
  type T = MyT
  class MyT extends BaseT { ... }
  def foo = new MyT
}


You only have to go complex if you're doing something complex, like trait-ecosystems and ecosystem inheritance.

- Josh
Reply all
Reply to author
Forward
0 new messages