gpt4 book ai didi

scala - 为什么 Future.onSuccess 需要偏函数

转载 作者:行者123 更新时间:2023-12-04 12:30:30 26 4
gpt4 key购买 nike

我正在尝试使用 Future 将一些基本功能链接在一起s 从一个光滑的 Action 中返回,我遇到了一些非常微不足道的绊脚石。

两者andThenonSuccess方法需要一个 PartialFunction作为参数传递。我的理解可能有很大的缺陷,但在阅读了 anonymous functions 之后好像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

我收到一个编译错误:
[error]  found   : Unit => Unit
[error] required: PartialFunction[Unit,?]
[error] .onSuccess { println(_) }

最佳答案

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

  val f = Future.successful("test")

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

对于更高级的数据类型,我认为这更有用:
  val fOpt = Future.successful(Option("Test"))

fOpt.onSuccess({
case Some(x) => println(x)
case None => println("None")
})

真的,这可能只是来自 Actor api,因为当你 ask您不知道返回类型的转换,您需要对其进行模式匹配,因为它是 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")
})

关于scala - 为什么 Future.onSuccess 需要偏函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31253814/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com