Rodrigo Stv Rodrigo Stv - 2 months ago 16
Scala Question

Subclass list in scala to implement graph

I am studying how to implement a graph in scala and what id really like to have is a list of edges (assume already defined), like a List[Edge], but with a few extra methods, for returning all vertices for example. But lists are sealed (final?) And can't be subclassed.

How could I go about this?

object Main {

implicit def listToGraph(list: List[Edge]): Graph = new Graph(list)

class Graph(e: List[Edge]) {
def vertices() = (e.map(_.v1) ++ e.map(_.v2)).distinct
}

case class Edge(v1: Long, v2: Long)

def main(args: Array[String]): Unit = {
val e: List[Edge] = List(Edge(0, 1), Edge(0, 2))
e.vertices.foreach(println)
}
}


This code works -- in the sense that I can call
_.vertices
on a
List[Edge]
, but what I was really trying to do is have a class named Graph on which I can call any method from
List[Edge]
and
_.vertices

Answer

You could model your solution better by implicitly converting from graph to list instead:

case class Edge(v1: Long, v2: Long) 

case class Graph(e: List[Edge]) {
      def vertices() = (e.map(_.v1) ++ e.map(_.v2)).distinct
    } 

implicit def graphToList(graph: Graph): List[Edge] = graph.e 

val g = Graph(List(Edge(0, 1), Edge(0, 2))) 

g.head  // use graph as a list
Comments