Pregunta

I'm playing around with mixins and traits in Scala and I've come across a small issue, how do I (without overriding) access a class field from a mixin?

Here's my code:

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!"
}

Nothing too special really, but now I mix Friend into an object of Cat

val felix = new Cat("Felix") with Friend

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

How would I write it so that instead of it saying "Gets help" it says "Felix gets help"? That is, getting the value from the name field without having to extend Friend at the class definition? (I don't want all instances of Cat to also be a Friend)

¿Fue útil?

Solución

On the fly:

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

println(fred.getHelp())

or using another trait:

trait FriendWithName extends Friend {
  var name: String

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

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

or without trait Friend altogether:

val wilma = new Cat("Wilma") {
  def getHelp() = {
    name + " gets help"
  }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top