1

在下文中,我无法在+方法中引用特征的偏移值(第 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
4

1 回答 1

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

哈。晚安,好运。

于 2013-08-10T07:16:15.303 回答