为什么scala的模式加工在类型匹配的for循环中不起作用?
|
我正在编写一个API,让我可以访问远程文件系统. API返回文件和目录列表作为节点对象列表(父文件和目录).
我想只在一个目录上工作,忽略文件.我试过在for循环中使用类型模式匹配,但它不起作用: for {
dir: CSDir <- workarea.getChildren() // <-- I'm getting an error here complaining about type conversion
} {
println(dir)
}
下面是一个使用scala基本对象运行它而没有依赖关系的类似示例: val listOfBaSEObjects:List[Any] = List[Any]("a string",1:Integer);
for (x: String <- listOfObjects) {
println(x)
}
我最终在for循环的一侧使用常规模式匹配,并且工作正常: // This works fien
for (child <- workarea.getChildren()) {
child match {
case dir: CSDir => println(dir)
case _ => println("do not nothing")
}
}
题: 你能告诉我为什么第一个/第二个例子在scala 1.9中不起作用吗? 在“Scala编程”中,for循环被广告为使用与匹配相同的模式匹配,因此它应该起作用. 如果for和match不同,那么如果你能指出一些有更多细节的文章会很棒.分配中的模式匹配怎么样? 更新: 我不能接受一个答案,该答案表明不可能跳过for循环中的元素,因为这与“Scala中的Prog.”相矛盾.这是第23.1节中的一个片段:
确实以下示例工作得很好: scala> val list = List( (1,2),1,3,(3,4))
scala> for ((x,y) <- list) { println (x +","+ y) }
1,2
3,4
为什么然后类型匹配不起作用? 解决方法
这是
long-standing issue 900,之前已经讨论了很多次.常见的解决方法是使用以下内容:
for (y@(_y:String) <- listOfBaSEObjects) {
println(y)
}
Jason Zaugg在对上述票证的评论中提供了更好的版本: object Typed { def unapply[A](a: A) = Some(a) }
for (Typed(y : String) <- listOfBaSEObjects) {
println(y)
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
