Kartik Aiyer
Kartik Aiyer

Reputation: 591

Subclassing classes that have type parameters

Trying some basic graphing stuff in scala and ran into something which I think SO community can help with.

First. I have a graph trait defined

trait GraphLike[T] { ... }

and a sub-class

class DiGraph[T] extends GraphLike[T] { ... }

I also have a BreadthFirstSearch Class which looks like this:

class BreadthFirstSearch[ T ]( val graph: GraphLike[T], val sourceVertex: T ) extends Graphsearch.GraphSearch[ T ]{

I'm trying to use this in another class which looks like this:

class SAP[T]( val graph: DiGraph[T]) {

  class inSap[T]( val v: T, val w: T )
  {
    val bfsV  = new BreadthFirstSearch[T](graph, v)
  }
}

I'm running into a compiler error when calling new BreadthFirstSearch.

BreadthFirstSearch takes a GraphLike parameter. The SAP class has a graph: DiGraph[T] and DiGraph is a subclass of GraphLike, so I would expect to be able to call the constructor of BreadthFirstSearch using a graph parameter of type DiGraph because DiGraph is GraphLike.

However, the compiler says this:

type mismatch; found : com.KGraph.DiGraph[T(in class SAP)] required: com.KGraph.GraphLike[T(in class 
 inSap)]

Its doesn't like me using the sub-class DiGraph in place of a GraphLike. Any idea why this would happen? I'm guessing this may have to do with the Type Parameters. All the classes are invariant on the type parameter.

I didn't think anything other than the class constructor definitions were needed to help with this, however, if more code is needed to figure stuff out, please update and I will provide the code.

Upvotes: 0

Views: 101

Answers (1)

stew
stew

Reputation: 11366

When you defined your inner class:

  class inSap[T]( val v: T, val w: T )

You introduced a second type variable named T. So when you call new BreadthFirstSearch[T] that is using the T from inSap, not the T from SAP. You should just need to remove the type parameter from inSap, so that inside that class, T just refers the the type in the outer scope.

Upvotes: 3

Related Questions