I am learning scala but got stuck in a simple problem. I wanted to assign a value to a variable using foreach loop.
for example:
List A
foreach x in A { variable b = x; => then some operation => print result}
can you please let me know how I can achieve this in scala?
1) You can use .map
on list
if you want to process it and want a list of something else back (just like in maths f:A=>B)
input set
scala> val initialOrders = List("order1", "order2", "order3")
initialOrders: List[String] = List(order1, order2, order3)
function
scala> def shipOrder(order: Any) = order + " is shipped"
shipOrder: (order: Any)String
process input set and store output
scala> val shippedOrders = initialOrders.map(order => { val myorder = "my" + order; println(s"shipping is ${myorder}"); shipOrder(myorder) })
shipping is myorder1
shipping is myorder2
shipping is myorder3
shippedOrders: List[String] = List(myorder1 is shipped, myorder2 is shipped, myorder3 is shipped)
2) Or you can simply iterate with foreach
on list when you don't care about output from function.
scala> initialOrders.foreach(order => { val whateverVariable = order+ "-whatever"; shipOrder(order) })
Note
What is the difference between a var and val definition in Scala?
this is proper way of running a foreach operation on a List.
val list: List[T] = /* list definition */
list foreach { x => var a = x; /* some operation */ }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.