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?
String
itself is not a subtype of Iterable[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 (<:
):
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With