Scala 前向引用

Scala forward referencing

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

Location 里面的

LinkedLocations 是一个 Location 类型的数组,可以有一个位置可以通向的任意数量的位置。在这种情况下,房间 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))
}

我试过使它们成为惰性值,但最终导致堆栈溢出。 如何解决这样的前向引用问题? 有没有更好的设计方法?

这看起来像图形表示——通常通过将图形节点(在本例中为位置)与图形边缘(链接位置)解耦来避免前向引用。您通常可以通过哈希映射查找相邻信息。类似于:

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))