Scala'中的过滤;s代表循环

Scala'中的过滤;s代表循环,scala,Scala,我是Scala的新手,现在正在学习for语句。我读了这个教程 在本教程中,有一个例子 for (person: Person <- people if !person.female; name = person.name; if name.contains("Ewing")) println(name) 或者像这样: for(person: people) { String name = person.name; if (!person.femal

我是Scala的新手,现在正在学习for语句。我读了这个教程

在本教程中,有一个例子

for (person: Person <- people
    if !person.female;
    name = person.name;
    if name.contains("Ewing"))
  println(name)
或者像这样:

for(person: people) {
   String name = person.name;
   if (!person.female && name.contains("Ewing")) {
     println(name)
   }
}
如果第一个筛选条件“if!person.female;”不满足,是否执行操作(在本例中,name=person.name;)


谢谢

Scala
for
理解展开为
map
flatmap
filter
的组合。在您的例子中,
如果
实际上是在“循环”的这个“迭代”中出现在它前面的所有值的过滤器。因此,如果
条件不满足,循环将跳过此迭代,因此Java
for
循环的行为方式与Scala示例相同

例如,在REPL中尝试以下操作:

scala> val l = List(1, 2, 3, 4, 5, 6)
l: List[Int] = List(1, 2, 3, 4, 5, 6)

scala> for (i <- l
     |      if(i%2 == 0))
     |      println(i)
2
4
6

scala> 
试试看

for{
  x <- 1 to 10
  if x % 3 == 0
  y = println(f"x=$x")
  if x % 2 == 0
} {
  println(x)
}

这意味着
y=
行发生在第二个
if
过滤器之前。

我认为它不会计算以下表达式,因为这是一个使用和条件进行计算的常见实现。您可以在这里看到


当使用&

查看scala编译器生成的内容时,scala也有这种短路实现,编译为
scalac-Xprint:typer
。它给出:

  people.withFilter(((check$ifrefutable$1: typer.Person) => check$ifrefutable$1: @scala.unchecked match {
  case (person @ (_: Person)) => true
  case _ => false
}))
//filter is acting as your if-clause
.withFilter(((person: Person) => person.<female: error>.unary_!)).map(((person: Person) => {
  val name = person.name;
  scala.Tuple2(person, name)
}))
//Your next if-clause
.withFilter(((x$1) => x$1: @scala.unchecked match {
  case scala.Tuple2((person @ (_: Person)), (name @ _)) => name.contains("Ewing")
}))
//Print each of them
.foreach(((x$2) => x$2: @scala.unchecked match {
        case scala.Tuple2((person @ (_: Person)), (name @ _)) => println(name)
      }))
    }
  }

上面的
用于理解使用
flatmap
map
。用Java
for
循环(
foreach
基本上是”)来思考也无助于找到原因。

另一个困惑来源:我想说,我不确定
for(p:Person
for{
  x <- 1 to 10
  if x % 3 == 0
  y = println(f"x=$x")
  if x % 2 == 0
} {
  println(x)
}
x=3
x=6
x=9
6
  people.withFilter(((check$ifrefutable$1: typer.Person) => check$ifrefutable$1: @scala.unchecked match {
  case (person @ (_: Person)) => true
  case _ => false
}))
//filter is acting as your if-clause
.withFilter(((person: Person) => person.<female: error>.unary_!)).map(((person: Person) => {
  val name = person.name;
  scala.Tuple2(person, name)
}))
//Your next if-clause
.withFilter(((x$1) => x$1: @scala.unchecked match {
  case scala.Tuple2((person @ (_: Person)), (name @ _)) => name.contains("Ewing")
}))
//Print each of them
.foreach(((x$2) => x$2: @scala.unchecked match {
        case scala.Tuple2((person @ (_: Person)), (name @ _)) => println(name)
      }))
    }
  }
scala> for(x <- Option(1);
     | u <- scala.util.Left(2)
     | ) yield (x,u)
<console>:9: error: value map is not a member of scala.util.Left[Int,Nothing]
              u <- scala.util.Left(2)