我创造了一个名为“动物”的特性和两个类:狗和猫。狗和猫都有同伴类,它们存储生命的数量。我的猫对象有9个生命,我的狗对象有1个生命。我想向动物特性添加一个名为isAlive的函数,并在那里实现。isAlive函数需要访问动物的活动数量。我如何才能访问同伴类中的生命价值?
我是否应该将生命价值移到类中,并删除同伴类?
这是我的密码。
特性
package Animal
trait Animal {
def speak: String
def getDeaths: Int
def isAlive: Boolean = {
getDeaths < 1 // I want to replace 1 with the number of lives from the Dog or Cat
}
}猫类和伴生类
package Animal
class Cat(a: Int) extends Animal {
private var age: Int = a
private var deaths: Int = 0
def this() = this(0)
override def speak: String = {
if (this.isAlive) {
"Meow"
}
else {
"..."
}
}
// I want to do this in the trait
// override def isAlive: Boolean = this.deaths <= Cat.lives
def setAge(age: Int): Unit = this.age = age
def getAge: Int = this.age
def getDeaths: Int = this.deaths
def die(): Unit = this.deaths += 1
}
object Cat {
val lives: Int = 9
}发布于 2018-03-02 23:36:52
我将lives作为Animal特性中的一个抽象方法,类似于getDeaths (顺便说一句,Scala不遵循getters和setter的命名约定)。
如果您熟悉Java,那么scala中的伙伴对象类似于Java的static,这意味着objects的类型解析发生在编译时,并且不可能像使用class的方法和字段那样使用多态性。
以下是代码:
trait Animal {
def speak: String
def getDeaths: Int
def lives: Int
def isAlive: Boolean = {
getDeaths < lives
}
}
class Cat(a: Int) extends Animal {
override val lives: Int = 9
private var age: Int = a
private var deaths: Int = 0
def this() = this(0)
/* ... */
}或者,您可以在同伴对象中定义lives常量,并在重写lives方法时在具体类中引用它:
class Cat(a: Int) extends Animal {
override val lives: Int = Cat.lives
private var age: Int = a
private var deaths: Int = 0
def this() = this(0)
/* ... */
}
object Cat {
val lives = 9
}发布于 2018-03-02 23:52:00
要在一个lives中访问trait,就必须像@Alvean所指出的那样,它必须是该特性的一部分,或者您必须要求扩展该特性的类必须拥有它。
trait Animal { self: {val lives: Int} =>
def isAlive: Boolean = getDeaths < lives
. . .
}
class Cat(a: Int) extends Animal {
val lives = Cat.lives //required to be an Animal
. . .
}https://stackoverflow.com/questions/49078809
复制相似问题