如果后卫没有编译,正则表达式无法理解

Klu*_*ßer 11 scala

为什么以下内容无法编译

for {
    s <- List.empty[String]
    regex <- List.empty[scala.util.matching.Regex]
    regex(ss) = s
    if ss == "foo"
} yield s
Run Code Online (Sandbox Code Playgroud)

但删除 if

for {
    s <- List.empty[String]
    regex <- List.empty[scala.util.matching.Regex]
    regex(ss) = s
} yield s
Run Code Online (Sandbox Code Playgroud)

或者重新排列两个列表的顺序以便理解

for {
    regex <- List.empty[scala.util.matching.Regex]
    s <- List.empty[String]
    regex(ss) = s
    if ss == "foo"
} yield s
Run Code Online (Sandbox Code Playgroud)

编译?

Scalafiddle:http://scalafiddle.net/console/2519ff98d434cb522589f54a9c5fcf55

dev*_*kat 2

您可以使用以下命令查看翻译后的理解:

scalac -Xprint:all <file>.scala
Run Code Online (Sandbox Code Playgroud)

在第一个示例中,生成的代码如下所示(我稍微清理了输出):

scalac -Xprint:all <file>.scala
Run Code Online (Sandbox Code Playgroud)

问题似乎是子句直接在语句中withFilter使用表达式,但它的值没有在那里定义。我不确定这是否可以被视为语言规范或编译器中的缺陷。错误消息当然没有多大帮助。regex(ss)caseregex

您可以阅读Scala 语言规范第 6.19 章的详细信息。