“MyType” problem: Do I have to use abstract types (or generics) in Scala to return the actual class?

前端 未结 3 858
南旧
南旧 2020-12-08 17:41

I am not sure if there is a better way of doing this:

trait Animal {
  val name: String
  val weight: Int

  type SubAnimal <: Animal

  def updateName(n:         


        
3条回答
  •  余生分开走
    2020-12-08 18:02

    This should work:

    trait Animal[T] {
      self:T =>
    
      val name: String
      val weight: Int
    
      def updateName(n: String): T = returnMe(n, this.weight)
      def updateWeight(w: Int): T = returnMe(this.name, w)
      // Abstract protected method
      protected def returnMe(n: String, w: Int): T
    }
    
    case class Dog(name: String, weight: Int) extends Animal[Dog] {
      override def returnMe(n: String, w: Int): Dog = Dog("Dog: " + name, w)
    }
    
    case class Cat(name: String, weight: Int) extends Animal[Cat] {
       override def returnMe(n: String, w: Int): Cat = Cat("Cat: " + name, w)
    }
    

    Something like case class Cat(name: String, weight: Int) extends Animal[Dog] gets rejected by the compiler. Code stolen adapted from http://oldfashionedsoftware.com/2009/12/10/self-help/

提交回复
热议问题