Dyl*_*lan 8 type-systems scala type-parameter
我在理解scala的类型边界系统时遇到了一些麻烦.我要做的是创建一个持有者类,它包含可以迭代A类项目的T类项目.到目前为止,我所拥有的是:
class HasIterable[T <: Iterable[A], A](item:T){
def printAll = for(i<-item) println(i.toString)
}
val hello = new HasIterable("hello")
Run Code Online (Sandbox Code Playgroud)
类本身成功编译但尝试创建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")
^
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我原本希望hello
解决HasIterable[String, Char]
这个问题.这个问题怎么解决了?
Tom*_*ett 17
String
本身就不是一个亚型Iterable[Char]
,但它的皮条客,WrappedString
是.为了允许您的定义使用隐式转换,您需要使用视图bound(<%
)而不是upper类型bound(<:
):
class HasIterable[T <% Iterable[A], A](item:T){
def printAll = for(i<-item) println(i.toString)
}
Run Code Online (Sandbox Code Playgroud)
现在您的示例将起作用:
scala> val hello = new HasIterable("hello")
hello: HasIterable[java.lang.String,Char] = HasIterable@77f2fbff
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2293 次 |
最近记录: |