ope*_*sas 4 closures scala tuples
我有一个元组列表,我想遍历并获取每个元素的值.
这是代码:
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((), ())
Run Code Online (Sandbox Code Playgroud)
到目前为止,这么好,但是
scala> myTuples.map{ println _._1 }
<console>:1: error: ';' expected but '.' found.
myTuples.map{ println _._1 }
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
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 }
Run Code Online (Sandbox Code Playgroud)
声明变量,并使用括号做了伎俩,但我想知道为什么其他选项不起作用
这些都很好
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) }
Run Code Online (Sandbox Code Playgroud)
我在scala的第一步中发生的事情是,坚持一点点你得到你想要的东西,但你不确定为什么你尝试的第一个选项不起作用......
对于不起作用的选项:
scala> myTuples.map{ println _._1 }
Run Code Online (Sandbox Code Playgroud)
简短回答:在Scala中,你总是需要使用parens围绕println论证.答案很长: Scala只推断中缀方法的括号,意味着表单的代码object method argument被解释为object.method(argument).没有指定对象,因此不推断括号.你可以直接看到这个:
scala> println "Boom!"
<console>:1: error: ';' expected but string literal found.
println "Boom!"
^
Run Code Online (Sandbox Code Playgroud)
接下来,myTuples.map{ println(_._1) }.我不能立即清楚为什么这不起作用,因为这应该相当于作为该回答这个问题显示,占位符/部分地施加方法语法适用于尽可能小的范围.所以等效的代码就是myTuples.map{ x => println(x._1) },这是有效的.myTuples.map { println(x => x._1) }.由于scala没有足够的信息来推断类型x,因此会出现"缺少参数类型"错误.
关于myTuples.map{ val (id, name) = _ },占位符用于匿名函数,而在这里你是初始化val的.
然后myTuples.map{ x => println x },你也错过了parens.
最后,适合您的选项您的工作解决方案现在正常.myTuples.map{ x => println("id: %s, name: %s".format(id, name)) }实际上并不起作用(查看它打印出来的数据).我的猜测,如果你已经定义id并name在REPL中,那些是正在打印的值.
我做你想做的事情的解决方案是:
myTuples foreach {
case (id, name) => printf("id: %s, name: %s\n", id, name)
}
Run Code Online (Sandbox Code Playgroud)
要么
myTuples foreach {
x => printf("id: %s, name: %s\n", x._1, x._2)
}
Run Code Online (Sandbox Code Playgroud)
我想你想要的东西:
myTuples map { case(id, name) => println(id+": "+name) }
Run Code Online (Sandbox Code Playgroud)