Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issue `object Foo { val 1 = 2 }` in scala

Tags:

methods

scala

I found this issue of scala: https://issues.scala-lang.org/browse/SI-4939

Seems we can define a method whose name is a number:

scala> object Foo { val 1 = 2 }
defined module Foo

But we can't invoke it:

scala> Foo.1
<console>:1: error: ';' expected but double literal found.
       Foo.1

And we can invoke it inside the object:

scala> object O { val 1 = 1; def x = 1 }
defined module O
scala> O.x
res1: Int = 1

And follow will throw error:

scala> object O { val 1 = 2; def x = 1 }
defined module O
scala> O.x
scala.MatchError: 2
    at O$.<init>(<console>:5)
    at O$.<clinit>(<console>)
    at .<init>(<console>:7)
    at .<clinit>(<console>)
    at RequestResult$.<init>(<console>:9)

I use scalac -Xprint:typer to see the code, the val 1 = 2 part is:

<synthetic> private[this] val x$1: Unit = (2: Int(2) @unchecked) match {
    case 1 => ()
}

From it, we can see the method name changed to x$1, and only can be invoked inside that object.

And the resolution of that issue is: Won't Fix

I want to know is there any reason to allow a number to be the name of a method? Is there any case we need to use a "number" method?

like image 475
Freewind Avatar asked Aug 24 '11 14:08

Freewind


1 Answers

There is no name "1" being bound here. val 1 = 2 is a pattern-matching expression, in much the same way val (x,2) = (1,2) binds x to 1 (and would throw a MatchError if the second element were not thet same). It's allowed because there's no real reason to add a special case to forbid it; this way val pattern matching works (almost) exactly the same way as match pattern-matching.

like image 135
RM. Avatar answered Sep 18 '22 13:09

RM.