在创建时使用for循环填充不可变映射

时间:2015-05-31 19:18:37

标签: scala dictionary collections initialization immutability

我的地图如下所示:

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

我想做类似的事情:

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

而不是长的复制/粘贴列表,如:

  (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), ...

但是我得到了

  

类型不匹配,预期:( NotInferedA,NotInferedB),实际:单位

为什么会这样,我怎么能克服这个?

1 个答案:

答案 0 :(得分:4)

问题是你的理解不会返回任何东西。 以下是您的问题的两种不同解决方案。我个人更喜欢第二个。

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

编辑:

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
}