In response to a comment from another question, I tried putting this code into Scala:
trait Foo
new Foo { self =>
val self.x = 3
}
It doesn't compile, of course, but the error is puzzling me:
recursive value x$1 needs type
val self.x = 3
^
How did this code get past the parser?
The -Xprint:parse
is also kind of bizarre:
<synthetic> private[this] val x$1 = 3: @scala.unchecked match {
case self.x => ()
}
Is that a match
in the type annotation for 3
? edit: Apparently not; that's the syntax for annotations.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With