向 scala yield 语句添加副作用

Add side effects to scala yield statement

在下面的 scala for 循环中

private val tpath = for (csvPath <- CsvPaths
  if new java.io.File(csvPath).exists()
) yield csvPath

我想添加一个 println 副作用 - 类似于以下内容:

private val tpath = for (csvPath <- CsvPaths
  if new java.io.File(csvPath).exists() {  // Following is illegal syntax
    println(s"Following path exists $csvPath")
  }
) yield csvPath

那么有什么语法可以将副作用添加到 for/yield 循环中吗?

for {
  csvPath <- CsvPaths
  _ = if(new java.io.File(csvPath).exists()) println(...)
} yield csvPath

for {
  csvPath <- CsvPaths
} yield {
  if(new java.io.File(csvPath).exists()) println(...)
  csvPath
}

您可以使用 _ 赋值:

for {
  csvPath <- CsvPaths
  if (new java.io.File(csvPath).exists())
  _ = println(s"Following path exists $csvPath")
} yield csvPath

当然,对于这个特定示例,您可以只使用一个块来获得收益:

for {
  csvPath <- CsvPaths
  if (new java.io.File(csvPath).exists())
} yield {
  println(s"Following path exists $csvPath")
  csvPath
}

但如果您想将调用放在 for/yield 链的 "middle" 中,之后有更多 <- 行,则上述技术很有用。