gpt4 book ai didi

scala - 为什么 Scala 模式匹配在类型匹配的 for 循环中不起作用?

转载 作者:行者123 更新时间:2023-12-04 06:23:10 26 4
gpt4 key购买 nike

我正在针对可让我访问远程文件系统的 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循环被宣传为使用与 match 相同的模式匹配所以它应该工作。
如果 for 和 match 不同,如果你能指点我一些更详细的文章,那就太好了。赋值中的模式匹配怎么样?
更新:
我不能接受这样一个答案,即不可能在 for 循环中跳过元素,因为这与“Prog. in scala”相矛盾。这是第 23.1 节中的一个片段:

pat <- expr ... The pattern pat gets matched one-by-one against all elements of that list. ... if the match fails, no MatchError is thrown. Instead, the element is simply discarded from the iteration


事实上,下面的例子工作得很好:
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)
}

关于scala - 为什么 Scala 模式匹配在类型匹配的 for 循环中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11394034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com