views:

118

answers:

2

Hi, 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.

+1  A: 

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.

wheaties
Do you find `Iterator.range(0, 4)` more readable than `0 until 4`?
Randall Schulz
I've been writing something on Scala Iterators and Python itertools. until is more concise.
wheaties
That will not return a `List`, and, furthermore, it does unexpected things on Scala 2.7 because `Range` is non-strict there.
Daniel
Nice post on your blog explaining the old way of 2.7: http://dcsobral.blogspot.com/2009/10/strict-ranges.html Very interesting and I must admit, I fell into this trap here.
wheaties
+6  A: 

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.

Daniel