runtime error - Scala forward referencing -
i'm new scala. i'm making game , have list of locations character can visit, of type location
. have case class , companion object achieve this.
linkedlocations
inside location
array of type location
, can have number of locations location can lead to. in case, room 1 leads room 2, , 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 in room 1",array(room2)) val room2: location = location("room 2","you in room 2",array(room1)) room1.linkedlocations.foreach(location=>println(location.name)) }
i've tried making them lazy vals end stack overflow. how fix forward referencing problems this? there better way design this?
this looks graph representation--typically forward references avoided decoupling graph nodes (locations in case) graph edges (linked locations). can neighboring information typically through hash map. like:
case class location(name: string, desc: string) object location { val none: location = location("none","none") val room1: location = location("room 1","you in room 1") val room2: location = location("room 2","you in room 2") val neighbormap: map[location, array[location]] = map( room1 -> array(room2), room2 -> array(room1) ) }
and can do:
neighbormap(room1).foreach(location => println(location.name))
Comments
Post a Comment