在方法中引用vals,在trait中返回新的trait实例

时间:2013-08-10 07:04:11

标签: scala

在下文中,我无法在+方法(第4行)中引用特征的偏移值。

目前正在编写this.offset始终为零。我想要的是+操作的LHS偏移。

应该怎么做?

trait Side {
  val offset: Int // <- I want to refer to this
  def +(side: Side) = new Object with Side {
    val offset: Int = this.offset + side.offset // but instead `this.offset` is 0
  }
}

case object Left extends Side {
  val offset = -1
}

case object Right extends Side {
  val offset = 1
}

(Left + Right).offset // -> (0 + 1) -> 1
(Right + Left).offset // -> (0 + -1) -> -1

1 个答案:

答案 0 :(得分:3)

以下是有效的,因为Side.this没有引用正在构建的匿名类。

匿名有其特权。

scala> :pa
// Entering paste mode (ctrl-D to finish)

trait Side {
  val offset: Int
  def +(side: Side) = new Side {
    val offset = Side.this.offset + side.offset
  }
}

// Exiting paste mode, now interpreting.

defined trait Side

scala> new Side { val offset = 1 }
res0: Side = $anon$1@7e070e85

scala> new Side { val offset = 2 }
res1: Side = $anon$1@5f701cd1

scala> res0+res1
res2: Side = Side$$anon$1@188ef927

scala> .offset
res3: Int = 3

首先猜测,认为这是一个阴影问题:

scala> :pa
// Entering paste mode (ctrl-D to finish)

trait Side {
  val offset: Int
  def +(side: Side) = new {
    val offset = Side.this.offset + side.offset
  } with Side
}

// Exiting paste mode, now interpreting.

defined trait Side

scala> new Side { val offset = 1 }
res5: Side = $anon$1@3fa76a13

scala> new Side { val offset = 2 }
res6: Side = $anon$1@465fb2a5

scala> res5+res6
res7: Side = Side$$anon$1@7e84d99c

scala> .offset
res8: Int = 3

哈。晚安,祝你好运。