views:

182

answers:

2

I've noticed the following behavior in scala when trying to unwrap tuples into vals:

scala> val (A, B, C) = (1, 2, 3)
<console>:5: error: not found: value A
       val (A, B, C) = (1, 2, 3)
            ^
<console>:5: error: not found: value B
       val (A, B, C) = (1, 2, 3)
               ^
<console>:5: error: not found: value C
       val (A, B, C) = (1, 2, 3)
                  ^

scala> val (u, v, w) = (1, 2, 3)
u: Int = 1
v: Int = 2
w: Int = 3

Is that because scala's pattern matching mechanism automatically presumes that all identifiers starting with capitals within patterns are constants, or is that due to some other reason?

Thanks!

+9  A: 

From http://scala-programming-language.1934581.n4.nabble.com/scala-Question-about-naming-conventions-td2003522.html#a2003522 you can read

The initial capital letter has an advantage when pattern matching. Identifiers with an initial capital letter are considered to be values to match against instead of a variable to be bound.

aioobe
thanks for the ref aioobe!
Paul Milovanov
+10  A: 

Yes, and it gets worse:

val (i, j) : (Int, Int) = "Hello" -> "World"

The above will compile and fail at runtime with a ClassCastException. It is easy to forget that the (i, j) declaration is a pattern.

EDIT: for ziggystar, the Scala assignment rules state that in the statement:

val p = expr //or var

p can be either an identifier or a pattern (see section 15.7 of Programming in Scala, pp284). So for example, the following is valid:

val x :: y :: z :: rest = List(1, 2, 3, 4)

Taking this together with the fact that patterns are erased (i.e. parametric type information is unchecked) means that my original example will compile.

oxbow_lakes
That's interessting. But I don't get what you mean by pattern here. Can you please explain a bit more?
ziggystar
I've modified my answer
oxbow_lakes
Interesting error... perhaps you should point out it fails because that's equivalent to `Tuple2[Int, Int]`, which is type-erased to `Tuple2[Any, Any]`?
Daniel
@Daniel - why, you just have pointed it out! :-)
oxbow_lakes