Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse error of nested tuples in scala

When writing the following code in scala

var m = Map((0,1) -> "a")
m += ((0,2), "b") // compilation error

I'm getting the error

type mismatch;
 found   : Int(0)
 required: (Int, Int)

However the changing the syntax of the tuple from (X,Y) to (X -> Y) works

var m = Map((0,1) -> 'a)
m += ((0,2) -> 'b) // compiles file

Even though

((0,1).getClass == (0 -> 1).getClass) // is true
(0,1).isInstanceOf[Tuple2[_,_]] && (0 -> 1).isInstanceOf[Tuple2[_,_]] // both true

Why is that? What does scala think my nested tuple is?

like image 766
Elazar Leibovich Avatar asked Sep 08 '09 15:09

Elazar Leibovich


1 Answers

The reason is pretty simple (I think) and has to do with the fact that (on the Map trait):

m += (a -> b)

is shorthand for:

m = m.+(t2) //where t2 is of type Tuple2[A,B]

Obviously if you use a comma in the first example, Scala will interpret this as being a call to the method:

m = m.+(a, b)

This method does not exist on the Map trait. Method invocation rules mean that a -> b gets evaluated first (to the Tuple2) and hence the correct method is called. Note: Using an extra pair of parentheses works just fine:

m += ( (a,b) ) //works just fine but less readable
like image 102
oxbow_lakes Avatar answered Oct 16 '22 10:10

oxbow_lakes