scala用于yield设置值
我想创建 GridBagPanel.Constraints 列表。 我在 scala 编程书中读到,有一个很酷的 for-yield 构造,但我可能还没有理解它的正确工作方式,因为我的代码无法编译。如下:
val d = for {
i <- 0 until 4
j <- 0 until 4
} yield {
c = new Constraints
c.gridx = j
c.gridy = i
}
我想生成一个 List[Constraints] ,并为每个约束设置不同的 x,y 值,这样稍后当我添加组件时,它们将位于网格中。
I want to create a list of GridBagPanel.Constraints
.
I read it in the scala programming book, that there is a cool for-yield
construction, but I probably haven't understood the way it works correctly, because my code doesn't compile. Here it is:
val d = for {
i <- 0 until 4
j <- 0 until 4
} yield {
c = new Constraints
c.gridx = j
c.gridy = i
}
I want to generate a List[Constraints]
and for every constraint set different x,y values so later, when I later add the components, they're going to be in a grid.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需在
yield
块末尾返回c
即可获取Constraints
集合。要让它返回List
,请使用List
而不是Range
。就像这样:事实上,原始代码在 Scala 2.7 中不会执行您期望的操作,因为范围(如
Range
中)是不严格的。您可以在 Stack Overflow 或 Google 上查找它,但缺点是每次您在d
上查找元素时,它都会创建一个新的Constraint
。 Scala 2.8 中此行为已更改。You just need to return
c
at the end of theyield
block to get a collection ofConstraints
. To get it to return aList
, use aList
instead of aRange
. Like this:In fact, the original code would not do what you expected it to in Scala 2.7 because, there, ranges (as in
Range
) are non-strict. You may look it up on Stack Overflow or Google, but the short of it is that each time you looked up an element ond
, it would create a newConstraint
. This behavior has changed for Scala 2.8.试试这个:
我已经用对函数的调用替换了您的调用。我已将until 替换为Iterator.range(0,4),但我已将其返回到until。两者都是有效的代码,实际上含义相同。
Try this:
I've replaced your call with a call to a function. I had replaced until with Iterator.range(0,4) but I've returned it to until. Both are valid code and actually mean the same thing.