Scala type parameter bounds

I am having trouble understanding a scala type restriction system. What I'm trying to do is make a holder class that contains elements of type T that can iterate over elements of type A. What I still have:

class HasIterable[T <: Iterable[A], A](item:T){ def printAll = for(i<-item) println(i.toString) } val hello = new HasIterable("hello") 

The class itself compiles successfully, but trying to create a hello value gives me this error:

 <console>:11: error: inferred type arguments [java.lang.String,Nothing] do not conform to class HasIterable type parameter bounds [T <: Iterable[A],A] val hello = new HasIterable("hello") ^ 

I would expect hello be resolved as HasIterable[String, Char] in this case. How is this problem resolved?

+8
scala type-systems type-parameter
source share
1 answer

String itself is not a subtype of Iterable[Char] , but its pimp , WrappedString , is. For your definition to use implicit conversions, you need to use a binding ( <% ) instead of a top type binding ( <: :

 class HasIterable[T <% Iterable[A], A](item:T){ def printAll = for(i<-item) println(i.toString) } 

Now your example will work:

 scala> val hello = new HasIterable("hello") hello: HasIterable[java.lang.String,Char] = HasIterable@77f2fbff 
+17
source share

All Articles