Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`val (A) = (3)` is correct, but `val (A,B)=(2,3)` can't be compiled, why?

val A = 3
val (A) = (3)

Both correct. But:

val (A,B) = (2,3)

can't be compiled:

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

Why?

like image 564
Freewind Avatar asked Apr 06 '12 09:04

Freewind


1 Answers

In the second code snippet, it using pattern matching to do assessment.

It is translated to the follow code:

val Tuple(A, B) = Tuple2(2,3)

When Scala is doing pattern matching, variable starts with a upper case in the pattern is considered as an constant value (or singleton Object), so val (a, b) = (2, 3) works but not val (A, B) = (2, 3).

BTW, your first code snippet does not using pattern matching, it's just an ordinary variable assignment.

If you using Tuple1 explicitly, it will have same error.

scala> val Tuple1(Z) = Tuple1(3)
<console>:7: error: not found: value Z
       val Tuple1(Z) = Tuple1(3)

Here is some interesting example:

scala> val A = 10
A: Int = 10

scala> val B = 20
B: Int = 20

scala> val (A, x) = (10, 20)
x: Int = 20

scala> val (A, x) = (10, 30)
x: Int = 30

scala> val (A, x) = (20, 20)
scala.MatchError: (20,20) (of class scala.Tuple2$mcII$sp)
    at .<init>(<console>:9)
    at .<clinit>(<console>)
like image 177
Brian Hsu Avatar answered Nov 19 '22 13:11

Brian Hsu