ChazMcDingle
ChazMcDingle

Reputation: 675

Scala forward referencing

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?

Upvotes: 2

Views: 308

Answers (1)

Alfredo Gimenez
Alfredo Gimenez

Reputation: 2224

This looks like a graph representation--typically forward references are avoided by decoupling the graph nodes (locations in this case) from the graph edges (linked locations). You can look up neighboring information typically through a hash map. Something like:

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

And then you can do:

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

Upvotes: 6

Related Questions