Fill an immutable map with a loop to create

I have this card that looks like this:

val fields: Map[(Int, Int), Field] 

and I thought about doing something like:

 val fields: Map[(Int, Int), Field] = Map( for(a <- 0 to 10) { (0, a) -> new Field(this, 0, a) } ) 

instead of a long copy / paste list, for example:

  (0, 0) -> new Field(this, 0, 0), (1, 0) -> new Field(this, 1, 0), (2, 0) -> new Field(this, 2, 0), (3, 0) -> new Field(this, 3, 0), (4, 0) -> new Field(this, 4, 0), (5, 0) -> new Field(this, 5, 0), (6, 0) -> new Field(this, 6, 0), (7, 0) -> new Field(this, 7, 0), (8, 0) -> new Field(this, 8, 0), (0, 1) -> new Field(this, 0, 1), ... 

But I get

Type mismatch expected: (NotInferedA, NotInferedB), actual: Unit

Why is it and how can I overcome it?

+2
source share
1 answer

The problem is that your understanding does not return anything. Here are two different solutions to your problem. I personally would prefer the second.

 case class Field(map: Map[(Int, Int), Field], a: Int, b: Int) val fields: Map[(Int, Int), Field] = Map( (for(a <- 0 to 10) yield (0, a) -> new Field(fields, 0, a)): _* ) val fields: Map[(Int, Int), Field] = (0 to 10).map(a => (0, a) -> new Field(fields, 0, a)).toMap 

edit:

 case class Field(board: Board, x: Int, y: Int) class Board { val fields: Map[(Int, Int), Field] = (0 to 10).map(a => (0, a) -> new Field(this, 0, a)).toMap } 

 class Board { val fields: Map[(Int, Int), Field] = (for(a <- 0 to 10; b <- 0 to 10) yield (a, b) -> new Field(this, a, b)).toMap } 
+5
source

All Articles