1

If I declare a val 1 how can I get access to it without changing name val 1?

val 1 = ONE
def ONE = 1

print(1) // `1` should be a reference to ONE which I declared above.
barbara
  • 3,111
  • 6
  • 30
  • 58

2 Answers2

2

This does not declare a variable with the name 1:

val 1 = ONE

What it does instead is pattern matching - and the result is not useful.

Try this, and you'll get a pattern match error:

def ONE = 2
val 1 = ONE

Variables in Scala cannot have names that consists of only digits, or that start with a digit. You cannot declare a variable with the name 1.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • But I can write `var 1 = ONE` as well. And it's a misleading syntax. – barbara Mar 31 '15 at 18:25
  • 1
    That works the same as `val 1 = ONE` (pattern matching, not declaring a variable). – Jesper Mar 31 '15 at 18:26
  • Yes, this is surprising syntax, but pattern matching when defining a `val` or `var` can be very useful, especially when used with tuples. See, for example [Is it possible to have tuple assignment to variables in Scala?](http://stackoverflow.com/questions/6196678/is-it-possible-to-have-tuple-assignment-to-variables-in-scala) – Jesper Mar 31 '15 at 18:36
  • When I use tuples I declare a variable `var (a, b) = (1, 2)`. This isn't like my case. – barbara Mar 31 '15 at 20:42
  • @barbara I know that. It was just to show what the possibilities are with pattern matching. – Jesper Apr 01 '15 at 07:27
0

Like Jesper said it's pattern matching. Consider this code which is similar to yours:

def ONE_AND_TWO = (1, 2)
val (1, b) = ONE_AND_TWO
println(b) // prints 2
val (2, _) = ONE_AND_TWO //scala.MatchError: (1,2) (of class scala.Tuple2$mcII$sp)

In your case you have just single value instead of tuple. If you however want to name variable, value or function as close to 1 as possible you can use:

def `1` = ONE
Community
  • 1
  • 1
Marek Adamek
  • 500
  • 3
  • 7