/** 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
を理解することはできません基本的な使用法はあると思われる:Future.onComplete:メソッドのシグネチャに
result.onComplete({
case Success(listInt) => {
//Do something with my list
}
case Failure(exception) => {
//Do something with my error
}
})
この機能は、それが(ログ完了など)ユニットを返すなどの副作用を生じさせるのに便利なようだ 何が理解できないのは、このタイプの関数U
が返すものです。私たちが提供する関数の戻り値の型は本当に便利ですか? Scalaはどのように使用していますか?
同じ質問がonSuccess
とonFailure
編集に適用できる:それをより明確にするために、def onComplete[U](func: Try[T] => U)
def onComplete(func: Try[T] => Unit)
以上のメリットは何ですか?
編集:
Chirloは右である、タイプUの関数はより柔軟であり、我々はより簡単にユニットを返さない既存の関数を渡すことができます。
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
[http://docs.scala-lang.org/overviews/core/futures.html]先物と約束のための最良の場所 – GKV
はい@GKV私は 'Callbacks'セクションを一見しました。 'U'型の使用法が記述されていないように思われたので、私はそれほど助けになりませんでした。 –
あなたはすでに関数' val op:Try [Int] => Sting'を持っているとしましょう。 '[U]'でこれを 'onComplete(op)'のように使うことができます。 '[U]'がなければ、このようにしなければなりません: 'onComplete(op(_))'(追加の無名関数)。 – senia