为什么Future.onSuccess需要部分功能

Gol*_*ish 7 scala future concurrent.futures

我正在尝试使用Future从光滑动作返回的s将一些基本函数链接在一起,并且我正在尝试一些非常微不足道的绊脚石.

无论是andThenonSuccess方法需要一个PartialFunction作为参数传递.我的理解可能是相当有缺陷的,但在阅读了匿名函数后,似乎andThen需要知道你的匿名函数,以满足任何SuccessFailure输入.

鉴于onSuccess已经只满足了这个Success案例的原因,为什么它仍然需要PartialFunction

这段代码我指出了我遇到的问题:

val db = Database.forConfig("h2mem1")

try {
  val f = db.run(setupCommands)
    .onSuccess { println(_) }

  Await.ready(f, 10.seconds )
}
finally db.close
Run Code Online (Sandbox Code Playgroud)

我收到编译错误:

[error]  found   : Unit => Unit
[error]  required: PartialFunction[Unit,?]
[error]         .onSuccess { println(_) }
Run Code Online (Sandbox Code Playgroud)

Noa*_*oah 3

他们这样做是为了让你可以对结果进行模式匹配,尽管我同意这似乎没有必要,但我并没有真正使用并且onSuccess更喜欢我的未来:mapflatMap

  val f = Future.successful("test")

  f.onSuccess({
    case "test" => println("Worked")
    case x: String => println(s"Kind of worked: $x")
  })
Run Code Online (Sandbox Code Playgroud)

对于更高级的数据类型,我认为这更有用:

  val fOpt = Future.successful(Option("Test"))

  fOpt.onSuccess({
    case Some(x) => println(x)
    case None => println("None")
  })
Run Code Online (Sandbox Code Playgroud)

实际上,这可能只是来自 actor api,因为当您ask作为 actor 时,您不知道返回类型,您需要对其进行模式匹配,因为它是Any

  val actor:ActorRef = ???

  val fAny = actor ? "asking"

  fAny.onSuccess({
    case x:String => println(s"Something String $x")
    case x:Int => println(s"Something Int $x")
    case x => println(s"Something else $x")
  })
Run Code Online (Sandbox Code Playgroud)