Scala generic: require method to use class's type

I'm pretty new to Scala. I'm trying to write an abstract class whose methods will be required to be implemented on a subclass. I want to use generics to enforce that the method takes a parameter of the current class.

abstract class MySuper{
  def doSomething:(MyInput[thisclass]=>MyResult)
}
class MySub extends MySuper{
  override def doSomething:(MyInput[MySub]=>MyResult)
}

I know that thisclass above is invalid, but I think it kind of expresses what I want to say. Basically I want to reference the implementing class. What would be the valid way to go about this?

Answers


You can do this with a neat little trick:

trait MySuper[A <: MySuper[A]]{
  def doSomething(that: A)
}

class Limited extends MySuper[Limited]{
  def doSomething(that: Limited)
}

There are other approaches but I find this one works fairly well at expressing what you'd like.


Need Your Help

How to allocate more memory to a JAVA program when executed from MATLAB?

java multithreading matlab memory-management

Introduction: I have recently been working on a rather heavy computational JAVA program (ODE Solver and numerical optimization). I have implemented multithread and will soon get access to a rather ...

Amazon IAM permissions list only one bucket

amazon-web-services amazon-s3 amazon-iam

Currently I have group with a policy that looks like this: