我在理解 scala 的类型边界系统时遇到了一些困难。我想做的是创建一个持有者类,该持有者类持有 T 类型的项目,可以迭代 A 类型的项目。到目前为止,我所拥有的是:
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]
在这种情况下。这个问题是如何解决的呢?
String
本身不是 的子类型Iterable[Char]
,但其pimp http://www.artima.com/weblogs/viewpost.jsp?thread=179766, WrappedString
, 是。为了允许您的定义使用隐式转换,您需要使用视图绑定 http://www.scala-lang.org/node/130 (<%
)而不是类型上限 http://www.scala-lang.org/node/136 (<:
):
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] = HasIterable@77f2fbff
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)