Scala转发引用

时间:2016-09-12 21:16:13

标签: scala runtime-error case-class forward-reference

我是Scala的新手。我正在制作游戏,我有一个角色可以访问的位置列表,类型为Location。我有一个案例类和一个伴随对象来实现这一目标。

LinkedLocations内的{p> LocationLocation类型的数组,可以包含位置可以导致的任意数量的位置。在这种情况下,1号房间通向2号房间,反之亦然。

case class Location(name: String, desc: String, linkedLocations: Array[Location]){}

object Location {

  val none: Location = Location("none","none",Array(none))
  val room1: Location = Location("room 1","you are in room 1",Array(room2))
  val room2: Location = Location("room 2","you are in room 2",Array(room1))

  room1.linkedLocations.foreach(location=>println(location.name))
}

我试过让它们变得很懒,但最终会出现堆栈溢出。 如何修复这样的引用问题? 是否有更好的方法来设计它?

1 个答案:

答案 0 :(得分:6)

这看起来像图形表示 - 通常通过将图形节点(在这种情况下为位置)与图形边缘(链接位置)分离来避免前向引用。您可以通过哈希映射查找相邻信息。类似的东西:

case class Location(name: String, desc: String)

object Location {

  val none: Location = Location("none","none")
  val room1: Location = Location("room 1","you are in room 1")
  val room2: Location = Location("room 2","you are in room 2")

  val neighborMap: Map[Location, Array[Location]] = Map(
    room1 -> Array(room2),
    room2 -> Array(room1)
  )
}

然后你可以这样做:

neighborMap(room1).foreach(location => println(location.name))