Overriding subclass methods with subclassed arguments?

后端 未结 1 1623
眼角桃花
眼角桃花 2021-01-05 11:54

How can I force base methods to take in the same specific subclass instance when overriden by a subclass?

i.e.:

abstract class Animal {
  def mateWit         


        
相关标签:
1条回答
  • 2021-01-05 12:42
    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 like this:

    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 exception-throwing code needed; the type system handles it for you at compile-time!

    0 讨论(0)
提交回复
热议问题