Using Scala structural types with abstract types
- by Joshua Hartman
I'm trying to define a structural type defining anything that has an "add" method (for instance, a java collection or a java map). Using this, I want to define a few higher order functions that operate on a certain collection
object GenericTypes {
type GenericCollection[T] = { def add(value: T): java.lang.Boolean}
}
import GenericTypes._
trait HigherOrderFunctions[T, CollectionType[X] <: GenericCollection[X]] {
def map[V](fn: (T) => V): CollectionType[V]
....
}
class RichJList[T](list: List[T]) extends HigherOrderFunctions[T, java.util.List]
This does not compile with the following error
error: Parameter type in structural refinement may not refer to abstract type defined outside that same refinement
I tried removing the parameter on GenericCollection and putting it on the method:
object GenericTypes {
type GenericCollection = { def add[T](value: T): java.lang.Boolean}
}
import GenericTypes._
trait HigherOrderFunctions[T, CollectionType[X] <: GenericCollection]
class RichJList[T](list: List[T]) extends HigherOrderFunctions[T, java.util.List]
but I get another error:
error: type arguments [T,java.util.List] do not conform to trait HigherOrderFunctions's type parameter bounds [T,CollectionType[X] <: org.scala_tools.javautils.j2s.GenericTypes.GenericCollection]
Can anyone give me some advice on how to use structural typing with abstract typed parameters in Scala? Or how to achieve what I'm looking to accomplish? Thanks so much!