简体   繁体   English

存储从每个循环Scala获得的值

[英]Storing values obtained from for each loop Scala

Scala beginner who is trying to store values obtains in a Scala foreach loop but failing miserably. 谁是试图存储值斯卡拉初学者获得在斯卡拉foreach循环,但惨遭失败。 The basic foreach loop looks like this currently: 当前的基本foreach循环如下所示:

order.orderList.foreach((x: OrderRef) => {
   val references = x.ref}))

When run this foreach loop will execute twice and return a reference each time. 运行时,此foreach循环将执行两次,并每次返回一个引用。 I'm trying to capture the reference value it returns on each run (so two references in either a list or array form so I can access these values later) 我正在尝试捕获每次运行时返回的参考值(所以两个参考以列表或数组形式出现,以便以后可以访问这些值)

I'm really confused about how to go about doing this... 我真的很困惑如何去做...

I attempted to retrieve and store the values as an array but when ran, the array list doesn't seem to hold any values. 我试图检索和存储值作为一个数组,但跑的时候,数组列表似乎并没有持有任何值。

This was my attempt: 这是我的尝试:

val newArray = Array(order.orderList.foreach((x: OrderRef) => {
    val references = x.ref
  }))
  println(newArray)

Any advice would be much appreciated. 任何建议将不胜感激。 If there is a better way to achieve this, please share. 如果有更好的方法可以做到这一点,请分享。 Thanks 谢谢

Use map instead of foreach 使用map代替foreach

order.orderList.map((x: OrderRef) => {x.ref}))

Also val references = x.ref doesn't return anything. val references = x.ref也不会返回任何内容。 It create new local variable and assign value to it. 它创建新的局部变量并为其赋值。

Agree with answer 1, and I believe the reason is below: 同意答案1,我相信原因如下:

Return of 'foreach' or 'for' should be 'Unit', and 'map' is an with an changed type result like example below: “ foreach”或“ for”的返回值应为“ Unit”,而“ map”是类型更改后的结果,如以下示例所示:

def map[B](f: (A) ⇒ B): Array[B]

Compare To for and foreach , the prototype should be like this 比较forforeach ,原型应该是这样的

def foreach(f: (A) ⇒ Unit): Unit

So If you wanna to get an changed data which is maped from your source data, considering more about functions like map , flatMap , and these functions will traverse all datas like for and foreach (except with yield ), but with return values. 因此,如果您想获取从源数据map的更改后的数据,请考虑更多有关mapflatMap功能,这些功能将遍历所有数据,例如forforeach (带有yield除外),但带有返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM