0

I try to implement the following graph class in scala: case class NodeT

case class Node[T](i:T)

class Graph[N<:Node[T], +T](someNodes:Set[N], val edges:Set[(N,N)]) {
  val nodes: Set[N] = someNodes ++ edges.map(_._1) ++ edges.map(_._2)

  def addVortex(node:N)=new Graph(someNodes, edges)//just use someNodes instead of nodes + node
}

But there is an error saying

inferred type arguments [N,Nothing] do not conform to class Graph's type parameter bounds [N <: Node[T],+T]

Why does this happen?

2 Answers 2

1

I will just clarify @chengpohi's answer

There are two issues in your code.

Small issue: since type T is not mentioned in the Graph constructor, you should specify it directly like:

def addVertex(node: N) = new Graph[N, T](someNodes + node, edges)

Bigger issue: as @chengpohi mentioned type T could not be covaiant in Graph and invariant in Node simultaneously. So you should correct one of the definitions

case class Node[+T](i: T)

or

class Graph[N <: Node[T], T]

Reason is: mention type parameter T as covariant means, for instance, that Graph[Node[String], String] is a subtype of Graph[Node[String], AnyRef], but this creates a contradiction, through Node[String] is not subtype of Node[AnyRef], while it should according to your definition.

Sign up to request clarification or add additional context in comments.

Comments

1

If you want to enable variant type T in Graph[N<:Node[T], +T], you need to enable Node T be variant.

case class Node[+T](i:T)

1 Comment

Hi I am new to scala, may I know what's the difference between T and +T? Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.