I’m having some trouble understanding scala’s type bounds system. What I’m trying to do is make a holder class that holds items of type T that can iterate over items of type A. What I have so far is:
class HasIterable[T <: Iterable[A], A](item:T){
def printAll = for(i<-item) println(i.toString)
}
val hello = new HasIterable("hello")
The class itself successfully compiles but attempting to create the hello value gives me this error:
<console>:11: error: inferred type arguments [java.lang.String,Nothing] do
not conform to class HasIterable's type parameter bounds [T <: Iterable[A],A]
val hello = new HasIterable("hello")
^
I would have expected hello to resolve as a HasIterable[String, Char] in that case. How is this problem solved?
Stringitself is not a subtype ofIterable[Char], but its pimp,WrappedString, is. In order to allow your definition to make use of implicit conversions, you need to use a view bound (<%) instead of an upper type bound (<:):Now your example will work: