I want to create a list of GridBagPanel.Constraints
.
I read it in the scala programming b开发者_如何学Goook, 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.
You just need to return c
at the end of the yield
block to get a collection of Constraints
. To get it to return a List
, use a List
instead of a Range
. Like this:
val d = for {
i <- List.range(0, 4)
j <- List.range(0, 4)
} yield {
c = new Constraints
c.gridx = j
c.gridy = i
c
}
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 on d
, it would create a new Constraint
. This behavior has changed for Scala 2.8.
Try this:
def conCreate = {
val c = new Constraints
c.gridx = j
c.gridy = i
c
}
val d = for( i <- 0 until 4;
j <- 0 until 4 ) yield conCreate(i,j)
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.
精彩评论