Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala type parameter bounds

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?

like image 485
Dylan Avatar asked Jul 15 '11 21:07

Dylan


1 Answers

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
like image 84
Tom Crockett Avatar answered Sep 19 '22 14:09

Tom Crockett