Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala generic: require method to use class's type

Tags:

generics

scala

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?

like image 706
Ryan Kennedy Avatar asked Oct 01 '22 20:10

Ryan Kennedy


1 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.

like image 170
wheaties Avatar answered Oct 13 '22 11:10

wheaties