首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从特征中定义的方法中的同伴类中访问常量

从特征中定义的方法中的同伴类中访问常量
EN

Stack Overflow用户
提问于 2018-03-02 23:14:32
回答 2查看 128关注 0票数 0

我创造了一个名为“动物”的特性和两个类:狗和猫。狗和猫都有同伴类,它们存储生命的数量。我的猫对象有9个生命,我的狗对象有1个生命。我想向动物特性添加一个名为isAlive的函数,并在那里实现。isAlive函数需要访问动物的活动数量。我如何才能访问同伴类中的生命价值?

我是否应该将生命价值移到类中,并删除同伴类?

这是我的密码。

特性

代码语言:javascript
复制
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
  }
}

猫类和伴生类

代码语言:javascript
复制
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
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-02 23:36:52

我将lives作为Animal特性中的一个抽象方法,类似于getDeaths (顺便说一句,Scala不遵循getters和setter的命名约定)。

如果您熟悉Java,那么scala中的伙伴对象类似于Java的static,这意味着objects的类型解析发生在编译时,并且不可能像使用class的方法和字段那样使用多态性。

以下是代码:

代码语言:javascript
复制
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方法时在具体类中引用它:

代码语言:javascript
复制
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
}
票数 2
EN

Stack Overflow用户

发布于 2018-03-02 23:52:00

要在一个lives中访问trait,就必须像@Alvean所指出的那样,它必须是该特性的一部分,或者您必须要求扩展该特性的类必须拥有它。

代码语言:javascript
复制
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
  . . .
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49078809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档