问题
I have this map 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 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 I get
Type mismatch, expected: (NotInferedA, NotInferedB), actual: Unit
Why is this and how can I overcome this?
回答1:
The problem is that your for comprehension doesn't return anything. Here are two different solutions to your problem. I personally would prefer the second one.
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
}
来源:https://stackoverflow.com/questions/30561653/fill-immutable-map-with-for-loop-upon-creation