2

I'm new to Scala. I'm making a game and I have a list of locations that a character can visit, of type Location. I have a case class and a companion object to achieve this.

LinkedLocations inside Location is an array of type Location and can have any number of locations that a location can lead to. In this case, Room 1 leads to Room 2, and vice versa.

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

I've tried making them lazy vals but end up with a stack overflow. How do I fix forward referencing problems like this? Would there be a better way to design this?

4

1 回答 1

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))
于 2016-09-12T21:53:02.197 回答