Rodrigo Stv - 11 months ago 69

Scala Question

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`

`List[Edge]`

`List[Edge]`

`_.vertices`

Answer Source

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
```