scala - Fill immutable map with for loop upon creation -
i have map looks this:
val fields: map[(int, int), field]
and thought doing like:
val fields: map[(int, int), field] = map( for(a <- 0 10) { (0, a) -> new field(this, 0, a) } )
instead of long copy/paste list like:
(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
type mismatch, expected: (notinfereda, notinferedb), actual: unit
why , how can overcome this?
the problem comprehension doesn't return anything. here 2 different solutions problem. prefer second one.
case class field(map: map[(int, int), field], a: int, b: int) val fields: map[(int, int), field] = map( (for(a <- 0 10) yield (0, a) -> new field(fields, 0, a)): _* ) val fields: map[(int, int), field] = (0 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 10).map(a => (0, a) -> new field(this, 0, a)).tomap }
class board { val fields: map[(int, int), field] = (for(a <- 0 10; b <- 0 10) yield (a, b) -> new field(this, a, b)).tomap }
Comments
Post a Comment