【发布时间】:2012-04-16 09:45:43
【问题描述】:
我有一个元组列表,我想遍历并获取每个元素的值。
这是代码:
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((), ())
到目前为止,还不错,但是
scala> myTuples.map{ println _._1 }
<console>:1: error: ';' expected but '.' found.
myTuples.map{ println _._1 }
我也试过了:
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 }
声明变量并使用括号可以解决问题,但我想知道为什么其他选项不起作用
这些都很好
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) }
在我使用 scala 的第一步中,发生在我身上的是,坚持一点点你得到你想要的,但你不确定为什么你尝试的第一个选项不起作用......
【问题讨论】:
-
FWIW,
map用于转换集合的内容。由于您不关心结果,因此foreach是首选方法。 -
不错的提示,也让开发者的意图更加清晰