【发布时间】:2015-06-08 15:13:36
【问题描述】:
给定val l = List( List(0), List(1) )
for循环:
for {
x <- l
_ = println(x)
y <- x
} {println(y)}
//将打印:
List(0)
List(1)
0
1
打印顺序错误!!
不是翻译成下面这样吗? for-loop的翻译:
l.foreach(
x => {
println(x)
x.foreach(y => println(y))
}
)
List(0)
0
List(1)
1
---
我的问题:
- 为什么for循环不按直观顺序执行? (我期待结果是使用 foreach 的第二个示例)
- 我的翻译错了吗?
- 为什么我们必须在 for-condition 部分分配一些东西(例如
_ = print())? (只是print()不会编译)
【问题讨论】:
标签: scala for-loop functional-programming for-comprehension