在 Scala 中解包 Future[Option[MyType]]

Unpacking Future[Option[MyType]] in Scala

我是 Scala 和 Play Framework 的新手,所以我不太确定哪里出了问题。我正在尝试解压缩 Slick DB 控制器(Play Framework)给出的 Future[Option[MyType]] 。 MyType在代码中被称为BoundingBox:

  def getBoundingBoxByFileName(name: String) = {
    val selectByName = boundingBoxTableQuery.filter{ boundingBoxTable =>
      boundingBoxTable.name === name
    }
    db.run(selectByName.result.headOption)
  }

BoundingBox 类型有一个名为 product_name 的字段。要检索此字段,我执行以下操作:

  val boundingBoxFutOpt = BoundingBoxQueryActions.getBoundingBoxByFileName("some_file")

  val res = for {
    optBb : Option[db.BoundingBox] <- boundingBoxFutOpt
  } yield{
    for(bb : db.BoundingBox <- optBb) yield {
      println(s"${bb.product_name}")
    }
  }

虽然我没有编译错误,但此代码不会在输出中产生任何结果。如果我更改一些随机文本的 println 语句(不使用 bb 引用),它也不会打印在控制台上。在我看来,println 语句似乎从未执行过。

我会很感激关于这个问题的一些指导。

很可能您的程序在将来有机会 运行 println 之前终止。我想这会让你得到你想要的:

import scala.concurrent.Await
import scala.concurrent.duration.Duration

// your code here

Await.result(res, Duration.Inf)

在您上面的示例中,您运行正在创建一个线程,但没有给它完成执行的机会。上面的内容会阻塞,直到 future 完成。

您不应该在生产代码中使用 Await 是毫无意义的,因为完成的阻塞否定了在单独线程中使用代码 运行 的价值。