4

为了回应另一个问题的评论,我尝试将此代码放入 Scala:

trait Foo

new Foo { self =>
  val self.x = 3
}

当然,它不会编译,但错误让我感到困惑:

recursive value x$1 needs type
    val self.x = 3
             ^

这段代码是如何通过解析器的?

-Xprint:parse也有点奇怪:

    <synthetic> private[this] val x$1 = 3: @scala.unchecked match {
      case self.x => ()
    }

那是match类型注释中的a3吗?编辑:显然不是;这就是注解的语法

4

1 回答 1

7

Variable definitions in Scala are actually pattern matching. That is, when you write

val x = y
println(x)

That's basically the same as writing

y match {
  case x =>
    println(x)

This can easily be seen in things like this:

val List(a, b, c) = someList
val RegexPattern(year, month, date) = "2013-10-23"

Another thing that's valid is constant pattern matching:

object X {
  val One = 1
}

scala> val X.One = 1

scala> val X.One = 2
scala.MatchError: 2 (of class java.lang.Integer)

And anything with a parenthesis will call an extractor:

object Y {
  val ymd = """(\d\d\d\d)-(\d\d)-(\d\d)""".r
}

scala> val Y.ymd(year, month, day) = "2013-10-23"
year: String = 2013
month: String = 10
day: String = 23    

So, you see, there's nothing syntactically illegal with what you wrote, just the specifics.

于 2013-10-23T03:02:41.777 回答