0

At the moment, I have the following Scala code using the Scala Graph library:

val g = Graph.from(nodes, edges)
            // nodes: List[Table]; edges: List[LkUnDiEdge[Table,String]]
            // inferred - g: Graph[Table, LkUnDiEdge]

...

def nodeTransformer(innerNode: Graph[Table, LkUnDiEdge]#NodeT) = {
    val node = innerNode.value
    Some( root,
          DotNodeStmt(node.name, style(node)) )
}

You may notice the parameter to nodeTransformer is an inner type of the type of g. Similar code repeats the concrete Graph type or some of its type parameters in other places in the codebase.

Type inference does not work in all places, and I'd like a way to express this type dependency without repeating the same explicit types throughout the code. As an example, the C++ typeof operator would allow me to rewrite the function as follows:

def nodeTransformer(innerNode: typeof(g)#NodeT) = {
    ...
}

What is the sane way to express such static type dependencies in Scala when type inference fails?

skoy
  • 266
  • 2
  • 10

1 Answers1

0

What about:

def nodeTransformer(innerNode: g.NodeT) = {
    ...
}

In contrast with C++ typeof, you should pass innerNode exactly for g, but not any other Graph instance (even with same type): What is meant by Scala's path-dependent types?

P.S. To extract type from generic (without type member inside) - How to capture T from TypeTag[T] or any other generic in scala?

Community
  • 1
  • 1
dk14
  • 22,206
  • 4
  • 51
  • 88
  • The problem is that `nodeTransformer` is passed as a parameter to a different method (specifically as `inodeTransformer` of [toDot](http://scala-graph.org/guides/dot.html)), and the type of that argument is required to be `Graph[Table,LkUnDiEdge]#NodeT => Option[...]`. `g.NodeT` is incompatible with that required type. – skoy Dec 04 '14 at 10:35
  • you could try `innerNode:Graph[g.N,g.E]#NodeT`; N and E are unreachable as type members, but you can capture them using http://stackoverflow.com/questions/26053319/how-to-capture-t-from-typetagt-or-any-other-generic-in-scala – dk14 Dec 04 '14 at 10:52
  • Oddly enough [this code](http://pastebin.com/QX7LaAGc) works. I'm going to mark this answer as accepted. It is somewhat of killing a bug with a cannon, though, so I'm holding out hope someone can point out a saner way to achieve the same effect in Scala. – skoy Dec 04 '14 at 13:19
  • agree. actually i'd prefer some built-in mechanizm for scala to capture generics, but didn't find any. – dk14 Dec 04 '14 at 13:28