Overriding subclass methods with subclass arguments?

How can I force the base methods to accept in the same concrete instance of the subclass when overriding the subclass?

i.e:.

abstract class Animal { def mateWith(that: Animal) } class Cow extends Animal { override def mateWith...? } 

Logically, Cow should be able to mateWith only Cow . However, if I do override def mateWith(that: Cow) , this does not actually override the base class method (which I want, since I want to ensure it exists in a subclass).

I can check to make sure the other instance is of type Cow, and throw an exception if this is not the case - is this my best option? What if I have more animals? I would have to repeat the exception code.

+6
override inheritance scala
source share
1 answer
 abstract class Animal[T <: Animal[T]] { def mateWith(that: T) } class Cow extends Animal[Cow] { override def mateWith(that: Cow) { println("cow") } } class Dog extends Animal[Dog] { override def mateWith(that: Dog) { println("dog") } } 

And use it as follows:

 scala> (new Cow).mateWith(new Cow) cow scala> (new Cow).mateWith(new Dog) <console>:17: error: type mismatch; found : Dog required: Cow (new Cow).mateWith(new Dog) ^ 

No code is required to throw exceptions; the type system processes it for you at compile time!

+11
source share

All Articles