斯卡拉新手有元组和封闭的麻烦
我有一个元组列表,我想遍历并获取每个元素的值.
这是代码: scala> val myTuples = Seq((1,"name1"),(2,"name2")) myTuples: Seq[(Int,java.lang.String)] = List((1,name1),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,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: name2 res22: Seq[Unit] = List((),()) scala> myTuples.map{ x => println(x._1) } 我在scala的第一步中发生的事情是,坚持一点点你得到你想要的东西,但你不确定为什么你尝试的第一个选项不起作用…… 解决方法
对于不起作用的选项:
scala> myTuples.map{ println _._1 } 简短的回答:在Scala中,你总是需要在println的论证中使用parens.答案很长:Scala只推断中缀方法的括号,这意味着表单对象方法参数的代码被解释为object.method(argument).没有指定对象,因此不推断出括号.你可以直接看到这个: scala> println "Boom!" <console>:1: error: ';' expected but string literal found. println "Boom!" ^ 接下来,myTuples.map {println(_._ 1)}.我不能立即清楚为什么这不起作用,因为这应该等同于myTuples.map {x => println(x._1)},有效.如the answers to this question所示,占位符/部分应用的方法语法适用于尽可能小的范围.因此,等效代码将是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))},实际上没有工作(查看它打印出来的数据).我猜你是否已经在REPL中定义了id和name,那些是要打印的值.您的工作解决方案现在正常. 我做你想做的事情的解决方案是: myTuples foreach { case (id,name) => printf("id: %s,name: %sn",id,name) } 要么 myTuples foreach { x => printf("id: %s,x._1,x._2) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |