I was trying to translate a snippet from Java into Scala. It is an infinite tree structure.
class Node {
public Node(Map<String, Node> routes) {}
}
class Factory {
public Map<String, Node> buildRoutes() {
Map<String, Node> routes = new HashMap<>();
asList("one", "two").forEach(key -> routes.put(key, new Node(routes));
return routes;
}
It is working just fine. Once I translated the snipped above to Scala I noticed a problem with Map. Looks like in Scala stock mutable and immutable maps are not compatible.
So I have to use mutable map type in the field Node. As for me it looks weird cause my map is not mutable. It is not changed in Node and Node has to know slightly more about its dependency that it should.
import scala.collection.mutable
case class Node(routes: mutable.Map[String, Node])
object Factory {
def buildRoutes(): mutable.Map[String, Node] = {
val routes = new mutable.HashMap[String, Node]
List("one", "two").foreach(key => routes.put(key, Node(routes)))
routes
}
}
I would be glad to see an alternative solution where Node.routes is an immutable map.