为什么 Future.onSuccess 需要部分函数
Why does Future.onSuccess require a partial function
我正在尝试使用从灵活操作返回的 Future
s 将一些基本函数链接在一起,但我遇到了一些非常琐碎的绊脚石。
andThen
和 onSuccess
方法都需要将 PartialFunction
作为参数传递。我的理解可能有很大的缺陷,但在阅读了 anonymous functions 之后,似乎 andThen
需要知道您的匿名函数以满足任何 Success
或 Failure
输入。
鉴于 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(_) }
好吧,你可以只传一个 PartialFunction
,如果它需要一个:
db.run(setupCommands).onSuccess(PartialFunction(println))
或者:
db.run(setupCommands).onSuccess { case result => println(result) }
他们这样做是为了让你可以对结果进行模式匹配,虽然我同意这似乎没有必要,但我并没有真正使用 onSuccess
并且更喜欢 map
和 flatMap
我的期货:
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")
})
真的,这可能只是来自演员 api,因为当你 ask
一个你不知道 return 类型的演员时,你需要对其进行模式匹配,因为这是 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")
})
我正在尝试使用从灵活操作返回的 Future
s 将一些基本函数链接在一起,但我遇到了一些非常琐碎的绊脚石。
andThen
和 onSuccess
方法都需要将 PartialFunction
作为参数传递。我的理解可能有很大的缺陷,但在阅读了 anonymous functions 之后,似乎 andThen
需要知道您的匿名函数以满足任何 Success
或 Failure
输入。
鉴于 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(_) }
好吧,你可以只传一个 PartialFunction
,如果它需要一个:
db.run(setupCommands).onSuccess(PartialFunction(println))
或者:
db.run(setupCommands).onSuccess { case result => println(result) }
他们这样做是为了让你可以对结果进行模式匹配,虽然我同意这似乎没有必要,但我并没有真正使用 onSuccess
并且更喜欢 map
和 flatMap
我的期货:
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")
})
真的,这可能只是来自演员 api,因为当你 ask
一个你不知道 return 类型的演员时,你需要对其进行模式匹配,因为这是 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")
})