在scala中使用traits时,类需要是抽象错误

时间:2014-02-01 10:12:58

标签: scala

以下是课程以及它延伸到的特性:

class Atom(var x: Double, var y: Double, var z: Double) extends AtomTrait{

  private var name: String = null 

  private var coords = Vector(this.x,this.y,this.z)

  def setCoords(x: Double, y: Double, z: Double){ 

    this.x = x 
    this.y = y 
    this.z = z

  }

  def getCoords = coords

  def setName(name: String){ this.name = name }

  def getName = this.name

}

trait AtomTrait {

  def getCoords

  def setCoords

  def setName(name: String)

  def getName: String 

}

我收到class Atom needs to be abstract, since method setCoords in trait AtomTrait of type => Unit is not defined

的错误

我认为我的setCoords方法返回Unit,因为它只为私有变量赋值。我做错了什么?

1 个答案:

答案 0 :(得分:3)

setCoords的签名应为:

trait AtomTrait {
  def setCoords(x: Double, y: Double, z: Double)
}

如果需要不同的坐标类型,可以使特征具有通用性:

trait AtomTrait[C] {

  def getCoords: C

  def setCoords(coords: C)
}

class Atom(var x: Double, var y: Double, var z: Double) extends AtomTrait[(Double, Double, Double)] {

  def setCoords(coords: (Double, Double, Double)) {
    coords match {
        case (x, y, z) => {
            this.x = x 
            this.y = y 
            this.z = z
        }
    }
  }

  def getCoords = (x, y, z)
}