2011-07-15 173 views
8

我在理解scala的类型范围系统时遇到了一些麻烦。我想要做的就是保存类型T的项目,可以遍历A型的项目我至今是一个holder类:Scala类型参数范围

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

val hello = new HasIterable("hello") 

本身成功编译的类,但在尝试创建在hello值给我这个错误:

<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") 
      ^

我本来期望hello解决在这种情况下,一个HasIterable[String, Char]。这个问题如何解决?

回答

17

String本身不是Iterable[Char]的子类型,但它的pimp,WrappedString是。为了让您的定义利用隐式转换,你需要使用一个view bound<%),而不是一个upper type bound<:):

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

现在您的示例将工作:

scala> val hello = new HasIterable("hello")    
hello: HasIterable[java.lang.String,Char] = [email protected] 
+1

会你介意解释为什么这个工作(而另一个不)? – dhg

+0

这对我有用,谢谢!是的,为什么<%在这种情况下工作? --aha我看到你的编辑。谢谢:) – Dylan

+0

@pelotom:很好的解释。谢谢! – dhg