Fill immutable map with for loop upon creation

六月ゝ 毕业季﹏ 提交于 2019-12-24 02:21:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!