Seb*_*ber 5 asynchronous scala future
/** When this future is completed, either through an exception, or a value,
* apply the provided function.
*
* If the future has already been completed,
* this will either be applied immediately or be scheduled asynchronously.
*
* $multipleCallbacks
* $callbackInContext
*/
def onComplete[U](func: Try[T] => U)(implicit executor: ExecutionContext): Unit
Run Code Online (Sandbox Code Playgroud)
基本用法似乎是:
result.onComplete({
case Success(listInt) => {
//Do something with my list
}
case Failure(exception) => {
//Do something with my error
}
})
Run Code Online (Sandbox Code Playgroud)
这个函数似乎对产生副作用很有用,因为它返回Unit(就像记录完成一样)我不明白这个U函数返回的是什么类型.我们提供的函数的返回类型是否真的有用?它是如何被Scala使用的?
同样的问题也适用于onSuccess和onFailure
编辑:以使其更清晰,有什么好处def onComplete[U](func: Try[T] => U)了def onComplete(func: Try[T] => Unit)?
编辑:
Chirlo是对的,U型的功能更灵活,我们可以更容易地传递不返回Unit的现有功能.
type T = String
def onComplete[U](func: Try[T] => U): Unit = { }
def onComplete2(func: Try[T] => Unit): Unit = { }
// Existing function that does not return Unit
def log[T]( t : Try[T]): Int = 0
onComplete(log) // This compiles fine
onComplete2(log) // This does not compile
Run Code Online (Sandbox Code Playgroud)
使得功能更加灵活。如果它返回Unit,您可以只向它传递函数Try[T] => Unit,但是通过返回U,您可以向它传递任何Try[T]您可能已经拥有的作为参数的函数。例如:
def log[T]( t : Try[T]): Int = //write to file and return 0 if Ok, else 128
Run Code Online (Sandbox Code Playgroud)
该函数有副作用,但也会返回一个值。您现在可以将此函数传递给您,Future尽管它不返回Unit,但结果会被丢弃,但您可以重用已经存在的函数。
| 归档时间: |
|
| 查看次数: |
1708 次 |
| 最近记录: |