Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a scala val definition with a dot in it produce an error in a later stage than parsing?

Tags:

syntax

scala

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.

like image 743
Owen Avatar asked Mar 22 '23 22:03

Owen


1 Answers

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.

like image 93
Daniel C. Sobral Avatar answered Mar 24 '23 21:03

Daniel C. Sobral