错误:类Animal需要是抽象的,因为:它有5个未实现的成员

blu*_*sky 11 scala

在下面的代码中我收到此错误:

class Animal needs to be abstract, since: it has 5 unimplemented members. /** As seen from class Animal, the 
 missing signatures are as follows. * For convenience, these are usable as stub implementations. */ def 
 favFood_=(x$1: Double): Unit = ??? def flyingType_=(x$1: scala.designpatterns.Strategy.Flys): Unit = ??? def 
 name_=(x$1: String): Unit = ??? def sound_=(x$1: String): Unit = ??? def speed_=(x$1: Double): Unit = ???
Run Code Online (Sandbox Code Playgroud)

如果我将类Animal的所有实例变量初始化为_则代码正确编译.这些错误意味着什么?

package scala.designpatterns

/**
 *
 * Decoupling
 * Encapsulating the concept or behaviour that varies, in this case the ability to fly
 *
 * Composition
 * Instead of inheriting an ability through inheritence the class is composed with objects with the right abilit built in
 * Composition allows to change the capabilites of objects at runtime
 */
object Strategy {

  def main(args: Array[String]) {

    var sparky = new Dog
    var tweety = new Bird

    println("Dog : " + sparky.tryToFly)
    println("Bird : " + tweety.tryToFly)
  }

  trait Flys {
    def fly: String
  }

  class ItFlys extends Flys {

    def fly: String = {
      "Flying High"
    }
  }

  class CantFly extends Flys {

    def fly: String = {
      "I can't fly"
    }
  }

  class Animal {

    var name: String
    var sound: String
    var speed: Double
    var favFood: Double
    var flyingType: Flys

    def tryToFly: String = {
      this.flyingType.fly
    }

    def setFlyingAbility(newFlyType: Flys) = {
      flyingType = newFlyType
    }

    def setSound(newSound: String) = {
      sound = newSound
    }

    def setSpeed(newSpeed: Double) = {
      speed = newSpeed
    }

  }

  class Dog extends Animal {

    def digHole = {
      println("Dug a hole!")
    }

    setSound("Bark")

    //Sets the fly trait polymorphically
    flyingType = new CantFly

  }

  class Bird extends Animal {

    setSound("Tweet")

    //Sets the fly trait polymorphically
    flyingType = new ItFlys
  }

}
Run Code Online (Sandbox Code Playgroud)

Rex*_*err 25

您必须初始化变量.如果不这样做,Scala假设您正在编写一个抽象类,子类将填充初始化.(如果你只有一个未初始化的变量,编译器会告诉你.)

写入= _使Scala填入默认值.

问题的关键是让你觉得会发生什么,当有人(例如,你,以后你忘了,你需要首先设置的东西)调用的东西,如声音不使用已经设置它.

(一般来说,您至少应该仔细考虑这是否是构建代码的正确方法;许多需要在使用前进行初始化的字段是安全的,没有任何机制来强制执行初始化,这就是问题.)