I have a List of tuples, and I'd like to traverse and get the value of each element.
this is the code:
scala> val myTuples = Seq((1, "name1"), (2, "name2"))
myTuples: Seq[(Int, java.lang.String)] = List((1,name1), (2,name2))
scala> myTuples.map{ println _ }
(1,name1)
(2,name2)
res32: Seq[Unit] = List((), ())
So far, so good, but
scala> myTuples.map{ println _._1 }
<console>:1: error: ';' expected but '.' found.
myTuples.map{ println _._1 }
I also tried with:
scala> myTuples.map{ println(_._1) }
<console>:35: error: missing parameter type for expanded function ((x$1) => x$1._1)
myTuples.map{ println(_._1) }
scala> myTuples.map{ val (id, name) = _ }
<console>:1: error: unbound placeholder parameter
myTuples.map{ val (id, name) = _ }
scala> myTuples.map{ x => println x }
<console>:35: error: type mismatch;
found : Unit
required: ?{val x: ?}
Note that implicit conversions are not applicable because they are ambiguous:
both method any2Ensuring in object Predef of type [A](x: A)Ensuring[A]
and method any2ArrowAssoc in object Predef of type [A](x: A)ArrowAssoc[A]
are possible conversion functions from Unit to ?{val x: ?}
myTuples.map{ x => println x }
Declaring the variable, and using parentheses did the trick, but I'd like to know why the other options didn't work
these worked fine
myTuples.map{ x => println("id: %s, name: %s".format(x._1, x._2)) }
scala> myTuples.map{ x => println("id: %s, name: %s".format(x._1, x._2)) }
id: 1, name: name1
id: 2, name: name2
res21: Seq[Unit] = List((), ())
scala> myTuples.map{ x => val(id, name) = x; println("id: %s, name: %s".format(id, name)) }
id: 1, name: name1
id: 2, name: name2
res22: Seq[Unit] = List((), ())
scala> myTuples.map{ x => println(x._1) }
What happens to me, with my first steps with scala, is that insisting a little bit you get what you want, but you are unsure why the first options you tried didn't work...