gpt4 book ai didi

scala - 错误 : class Animal needs to be abstract, 因为:它有 5 个未实现的成员

转载 作者:行者123 更新时间:2023-12-02 06:00:04 24 4
gpt4 key购买 nike

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

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 = ???

如果我将 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
}

}

最佳答案

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

编写 = _ 会使 Scala 填充默认值。

重点是让你思考当某人(例如你,在你忘记了你需要先设置一些东西之后)调用使用例如未设置的声音。

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

关于scala - 错误 : class Animal needs to be abstract, 因为:它有 5 个未实现的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18453406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com