如何从混合方法中访问类字段?

时间:2014-03-23 16:41:19

标签: scala mixins traits

我正在玩Scala中的mixins和traits,我遇到了一个小问题,我怎么(没有覆盖)从mixin访问一个类字段?

这是我的代码:

trait Friend {
  def getHelp() = "Gets help"
}

trait Speak {
  def speak(): String
}

class Person(var name: String) extends Speak with Friend {
  override def speak() = s"Hello, I am $name"
}

class Dog(var name: String) extends Speak with Friend {
  override def speak() = "woof woof!"
}

class Cat(var name: String) extends Speak {
  override def speak() = "meow!"
}

真的没什么特别的,但现在我将Friend混合到Cat

的对象中
val felix = new Cat("Felix") with Friend

println(felix.getHelp) // prints "Gets help"

我怎么写它,而不是说“获取帮助”,它说“Felix得到帮助”? 也就是说,从name字段获取值而不必在类定义中扩展Friend? (我不希望Cat的所有实例也都是Friend

1 个答案:

答案 0 :(得分:3)

动态:

val fred = new Cat("Fred") with Friend {
  override def getHelp() = {
    name + " " + super.getHelp()
  }
}

println(fred.getHelp())

或使用其他特征:

trait FriendWithName extends Friend {
  var name: String

  override def getHelp() = {
    name + " " + super.getHelp()
  }
}

val barney = new Cat("Barney") with FriendWithName
println(barney.getHelp())

或完全没有trait Friend

val wilma = new Cat("Wilma") {
  def getHelp() = {
    name + " gets help"
  }
}