如何在Scala的foreach中执行操作? [英] How to perform an operation in scala's foreach?

查看:692
本文介绍了如何在Scala的foreach中执行操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解使用foreach时如何执行操作.例如如何使用foreach

I am trying to understand how to perform an operation when using foreach. For e.g. how can I print element+1 of alist using foreach

scala>alist = List(1,3,5,7)
scala>alist.foreach(println(_+1)) #=> error: missing parameter type...
scala>alist.foreach(println(_).toInt + 1) #=> error: toInt is not a member of Unit

我知道下面有替代方法,但是我正在尝试是否可以使用foreach来完成.

I understand there are alternatives (below) but I am trying if it can be done using foreach.

scala>for(x<-alist) println(x+1)  #=> 2,4,6,8
scala>alist.map(x => println(x + 1)) #=> 2,4,6,8 

推荐答案

例如如何使用foreach将+1添加到列表的每个元素

For e.g. how can I add +1 to each element of a list using foreach

要回答更新的问题,您绝对可以使用foreach:

alist.foreach(x => println(x + 1))

您不能在println中使用占位符语法,因为编译器会将其推断为:

You can't use placeholder syntax inside println since the compler infers it as:

alist.foreach(x => println(x => x + 1))

根据它的扩展法则. println具有类型为Any的参数,因此无法使用plus方法将其绑定到具体类型.

According to it's expansion laws. println takes a parameter of type Any, so it can't bind it to a concrete type with a plus method.

如果您对占位符语法规则感兴趣,请参阅 Scala的隐藏功能

If you're interested in the rules of placeholder syntax, see Hidden features of Scala

由于列表是不可变的,并且foreach的返回类型为Unit,因此无法在Scala中使用foreach更改List[+A].您可以做的是使用map转换从现有列表中投影一个新列表:

You cannot mutate a List[+A] using foreach in Scala, since lists are immutable and foreach return type is Unit. What you can do is project a new list from an existing one using the map transformation:

scala> val list = List(1,2,3,4)
list: List[Int] = List(1, 2, 3, 4)

scala> val plusOneList = list.map(_ + 1)
plusOneList: List[Int] = List(2, 3, 4, 5)

如果查看foreach的签名,则会看到它具有一个函数:A => Unit,该函数采用类型A的元素并向后投射单元.此签名是副作用方法的标志,并且由于list是不可变的,因此对我们没有帮助.

If you look at the signature for foreach, you see that it takes a function: A => Unit, which takes an element of type A and projects back a Unit. This signature is a sign for a side effecting method and since list is immutable, that doesn't help us.

如果您使用了可变列表,例如ListBuffer,则可以对群体使用副作用:

If you used a mutable list, such as ListBuffer, then you could use side effects for population:

scala> val listBuffer = mutable.ListBuffer[Int]()
listBuffer: scala.collection.mutable.ListBuffer[Int] = ListBuffer()

scala> (0 to 4).foreach(x => listBuffer += x)

scala> listBuffer
res10: scala.collection.mutable.ListBuffer[Int] = ListBuffer(0, 1, 2, 3, 4)

这篇关于如何在Scala的foreach中执行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆