Valerin
Valerin

Reputation: 475

scala - calling methods of objects using for, foreach loops

I have this code:

val br = new ListBuffer[Piece]

  for(i <- 10 to 550 by 65) {
    br += new Brick(Point(x = i, y = 20, w = widthB, h = heighB))
  }

And a method draw(g, color) for Piece class. Now I would like to know how I can call that draw method for each Piece in the ListBuffer. I am trying in this way but I don't get why it's not functional:

br.foreach(x => draw(g, orange))

Thanks for any suggestions what I am doing wrong?

Upvotes: 1

Views: 1418

Answers (2)

hellraiser
hellraiser

Reputation: 1451

First of all val means constant and br couldn't be reassigned (br += X is equal to br = br + X)

Second, you'd better to refuse mutable state of br, you really don't need it. Just map range of Int into list of Bricks.

val br = (10 to 550 by 65) map (i => new Brick(Point(x = i, y = 20, w = widthB, h = heighB)))

Third, try to refuse OOP style while writing scala code. Use case classes for data representation and functions with pattern matching for operations with data. E.g. class Brick shouldn't have method draw. Better

case class Brick(p: Point) extends Piece

def draw(piece: Piece, color: Color): Unit = piece match {
   case Brick => //Some drawing rules
   case _ => throw new IllegalArgumentException
}

And then foreach will look like

br.foreach(item => draw(item, orange))

Upvotes: 1

Sergii Lagutin
Sergii Lagutin

Reputation: 10681

You forget specify object

br.foreach(x => x.draw(g, orange))

or

br.foreach(_.draw(g, orange))

Upvotes: 4

Related Questions