Movatterモバイル変換


[0]ホーム

URL:


Scala 3
3.7.4
LearnInstallPlaygroundFind A LibraryCommunityBlog
Scala 3
LearnInstallPlaygroundFind A LibraryCommunityBlog
DocsAPI
Generated with
Copyright (c) 2002-2025, LAMP/EPFL
Copyright (c) 2002-2025, LAMP/EPFL
Scala 3/scala/scala.concurrent/Future

Future

scala.concurrent.Future
See theFuture companion object
traitFuture[+T] extendsAwaitable[T]

AFuture represents a value which may or may not be currently available, but will be available at some point, or an exception if that value could not be made available.

Asynchronous computations are created by callingFuture.apply, which yields instances ofFuture. Computations are executed using anExecutionContext, which is usually supplied implicitly, and which is commonly backed by a thread pool.

import ExecutionContext.Implicits.globalval s = "Hello"val f: Future[String] = Future {  s + " future!"}f foreach {  msg => println(msg)}

Note that theglobal context is convenient but restricted: "fatal" exceptions are reported only by printing a stack trace, and the underlying thread pool may be shared by a mix of jobs. For any nontrivial application, see the caveats explained atExecutionContext and also the overview linked below, which explainsexception handling in depth.

Attributes

See also
Companion
object
Source
Future.scala
Graph
Supertypes
traitAwaitable[T]
classObject
traitMatchable
classAny
Known subtypes
objectnever

Members list

Grouped members

Callbacks

defandThen[U](pf:PartialFunction[Try[T],U])(implicitexecutor:ExecutionContext):Future[T]

Applies the side-effecting function to the result of this future, and returns a new future with the result of this future.

Applies the side-effecting function to the result of this future, and returns a new future with the result of this future.

This method allows one to enforce that the callbacks are executed in a specified order.

Note that if one of the chainedandThen callbacks throws an exception, that exception is not propagated to the subsequentandThen callbacks. Instead, the subsequentandThen callbacks are given the original value of this future.

The following example prints out5:

val f = Future { 5 }f andThen {  case r => throw new RuntimeException("runtime exception")} andThen {  case Failure(t) => println(t)  case Success(v) => println(v)}

Since this method executes asynchronously and does not produce a return value, any non-fatal exceptions thrown will be reported to theExecutionContext.

Type parameters

U

only used to accept any return type of the givenPartialFunction

Value parameters

pf

aPartialFunction which will be conditionally applied to the outcome of thisFuture

Attributes

Returns

aFuture which will be completed with the exact same outcome as thisFuture but after thePartialFunction has been executed.

Source
Future.scala
defforeach[U](f:T=>U)(implicitexecutor:ExecutionContext):Unit

Asynchronously processes the value in the future once the value becomes available.

Asynchronously processes the value in the future once the value becomes available.

WARNING: Will not be called if this future is never completed or if it is completed with a failure.

Since this method executes asynchronously and does not produce a return value, any non-fatal exceptions thrown will be reported to theExecutionContext.

Type parameters

U

only used to accept any return type of the given callback function

Value parameters

f

the function which will be executed if thisFuture completes with a result, the return value off will be discarded.

Attributes

Source
Future.scala
defonComplete[U](f:Try[T]=>U)(implicitexecutor:ExecutionContext):Unit

When this future is completed, either through an exception, or a value, apply the provided function.

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.

Note that the returned value off will be discarded.

Since this method executes asynchronously and does not produce a return value, any non-fatal exceptions thrown will be reported to theExecutionContext.

Multiple callbacks may be registered; there is no guarantee that they will be executed in a particular order.

The provided callback always runs in the provided implicitExecutionContext, though there is no guarantee that theexecute() method on theExecutionContext will be called once per callback or thatexecute() will be called in the current thread. That is, the implementation may run multiple callbacks in a batch within a singleexecute() and it may runexecute() either immediately or asynchronously. Completion of the Future must *happen-before* the invocation of the callback.

Type parameters

U

only used to accept any return type of the given callback function

Value parameters

f

the function to be executed when thisFuture completes

Attributes

Source
Future.scala

Polling

Returns whether the future had already been completed with a value or an exception.

Returns whether the future had already been completed with a value or an exception.

Note: using this method yields nondeterministic dataflow programs.

Attributes

Returns

true if the future was completed,false otherwise

Source
Future.scala

The current value of thisFuture.

The current value of thisFuture.

Note: using this method yields nondeterministic dataflow programs.

If the future was not completed the returned value will beNone. If the future was completed the value will beSome(Success(t)) if it contained a valid result, orSome(Failure(error)) if it contained an exception.

Attributes

Returns

None if theFuture wasn't completed,Some if it was.

Source
Future.scala

Transformations

defcollect[S](pf:PartialFunction[T,S])(implicitexecutor:ExecutionContext):Future[S]

Creates a new future by mapping the value of the current future, if the given partial function is defined at that value.

Creates a new future by mapping the value of the current future, if the given partial function is defined at that value.

If the current future contains a value for which the partial function is defined, the new future will also hold that value. Otherwise, the resulting future will fail with aNoSuchElementException.

If the current future fails, then the resulting future also fails.

Example:

val f = Future { -5 }val g = f collect {  case x if x < 0 => -x}val h = f collect {  case x if x > 0 => x * 2}g foreach println // Eventually prints 5Await.result(h, Duration.Zero) // throw a NoSuchElementException

Type parameters

S

the type of the returnedFuture

Value parameters

pf

thePartialFunction to apply to the successful result of thisFuture

Attributes

Returns

aFuture holding the result of application of thePartialFunction or aNoSuchElementException

Source
Future.scala

The returnedFuture will be successfully completed with theThrowable of the originalFuture if the originalFuture fails.

The returnedFuture will be successfully completed with theThrowable of the originalFuture if the originalFuture fails.

If the originalFuture is successful, the returnedFuture is failed with aNoSuchElementException.

This future may contain a throwable object and this means that the future failed. Futures obtained through combinators have the same exception as the future they were obtained from. The following throwable objects are not contained in the future: -Error - fatal errors are not contained within futures -InterruptedException - not contained within futures - allscala.util.control.ControlThrowable exceptNonLocalReturnControl - not contained within futures

Instead, the future is completed with an ExecutionException that has one of the exceptions above as its cause. If a future is failed with ascala.runtime.NonLocalReturnControl, it is completed with a value from that throwable instead.

Attributes

Returns

a failed projection of thisFuture.

Source
Future.scala
deffallbackTo[U >:T](that:Future[U]):Future[U]

Creates a new future which holds the result of this future if it was completed successfully, or, if not, the result of thethat future ifthat is completed successfully.

Creates a new future which holds the result of this future if it was completed successfully, or, if not, the result of thethat future ifthat is completed successfully. If both futures are failed, the resulting future holds the throwable object of the first future.

Using this method will not cause concurrent programs to become nondeterministic.

Example:

val f = Future { throw new RuntimeException("failed") }val g = Future { 5 }val h = f fallbackTo gh foreach println // Eventually prints 5

Type parameters

U

the type of the otherFuture and the resultingFuture

Value parameters

that

theFuture whose result we want to use if thisFuture fails.

Attributes

Returns

aFuture with the successful result of this or thatFuture or the failure of thisFuture if both fail

Source
Future.scala
deffilter(p:T=>Boolean)(implicitexecutor:ExecutionContext):Future[T]

Creates a new future by filtering the value of the current future with a predicate.

Creates a new future by filtering the value of the current future with a predicate.

If the current future contains a value which satisfies the predicate, the new future will also hold that value. Otherwise, the resulting future will fail with aNoSuchElementException.

If the current future fails, then the resulting future also fails.

Example:

val f = Future { 5 }val g = f filter { _ % 2 == 1 }val h = f filter { _ % 2 == 0 }g foreach println // Eventually prints 5Await.result(h, Duration.Zero) // throw a NoSuchElementException

Value parameters

p

the predicate to apply to the successful result of thisFuture

Attributes

Returns

aFuture which will hold the successful result of thisFuture if it matches the predicate or aNoSuchElementException

Source
Future.scala
defflatMap[S](f:T=>Future[S])(implicitexecutor:ExecutionContext):Future[S]

Creates a new future by applying a function to the successful result of this future, and returns the result of the function as the new future.

Creates a new future by applying a function to the successful result of this future, and returns the result of the function as the new future. If this future is completed with an exception then the new future will also contain this exception.

Example:

val f = Future { 5 }val g = Future { 3 }val h = for {  x: Int <- f // returns Future(5)  y: Int <- g // returns Future(3)} yield x + y

is translated to:

f flatMap { (x: Int) => g map { (y: Int) => x + y } }

Type parameters

S

the type of the returnedFuture

Value parameters

f

the function which will be applied to the successful result of thisFuture

Attributes

Returns

aFuture which will be completed with the result of the application of the function

Source
Future.scala
defflatten[S](implicitev:T<:<Future[S]):Future[S]

Creates a new future with one level of nesting flattened, this method is equivalent toflatMap(identity).

Creates a new future with one level of nesting flattened, this method is equivalent toflatMap(identity).

Type parameters

S

the type of the returnedFuture

Attributes

Source
Future.scala
defmap[S](f:T=>S)(implicitexecutor:ExecutionContext):Future[S]

Creates a new future by applying a function to the successful result of this future.

Creates a new future by applying a function to the successful result of this future. If this future is completed with an exception then the new future will also contain this exception.

Example:

val f = Future { "The future" }val g = f map { x: String => x + " is now!" }

Note that a for comprehension involving aFuture may expand to include a call tomap and orflatMap andwithFilter. Seescala.concurrent.Future#flatMap for an example of such a comprehension.

Type parameters

S

the type of the returnedFuture

Value parameters

f

the function which will be applied to the successful result of thisFuture

Attributes

Returns

aFuture which will be completed with the result of the application of the function

Source
Future.scala
defmapTo[S](implicittag:ClassTag[S]):Future[S]

Creates a newFuture[S] which is completed with thisFuture's result if that conforms toS's erased type or aClassCastException otherwise.

Creates a newFuture[S] which is completed with thisFuture's result if that conforms toS's erased type or aClassCastException otherwise.

Type parameters

S

the type of the returnedFuture

Value parameters

tag

theClassTag which will be used to cast the result of thisFuture

Attributes

Returns

aFuture holding the casted result of thisFuture or aClassCastException otherwise

Source
Future.scala
defrecover[U >:T](pf:PartialFunction[Throwable,U])(implicitexecutor:ExecutionContext):Future[U]

Creates a new future that will handle any matching throwable that this future might contain.

Creates a new future that will handle any matching throwable that this future might contain. If there is no match, or if this future contains a valid result then the new future will contain the same.

Example:

Future (6 / 0) recover { case e: ArithmeticException => 0 } // result: 0Future (6 / 0) recover { case e: NotFoundException   => 0 } // result: exceptionFuture (6 / 2) recover { case e: ArithmeticException => 0 } // result: 3

Type parameters

U

the type of the returnedFuture

Value parameters

pf

thePartialFunction to apply if thisFuture fails

Attributes

Returns

aFuture with the successful value of thisFuture or the result of thePartialFunction

Source
Future.scala
defrecoverWith[U >:T](pf:PartialFunction[Throwable,Future[U]])(implicitexecutor:ExecutionContext):Future[U]

Creates a new future that will handle any matching throwable that this future might contain by assigning it a value of another future.

Creates a new future that will handle any matching throwable that this future might contain by assigning it a value of another future.

If there is no match, or if this future contains a valid result then the new future will contain the same result.

Example:

val f = Future { Int.MaxValue }Future (6 / 0) recoverWith { case e: ArithmeticException => f } // result: Int.MaxValue

Type parameters

U

the type of the returnedFuture

Value parameters

pf

thePartialFunction to apply if thisFuture fails

Attributes

Returns

aFuture with the successful value of thisFuture or the outcome of theFuture returned by thePartialFunction

Source
Future.scala
deftransform[S](s:T=>S,f:Throwable=>Throwable)(implicitexecutor:ExecutionContext):Future[S]

Creates a new future by applying the 's' function to the successful result of this future, or the 'f' function to the failed result.

Creates a new future by applying the 's' function to the successful result of this future, or the 'f' function to the failed result. If there is any non-fatal exception thrown when 's' or 'f' is applied, that exception will be propagated to the resulting future.

Type parameters

S

the type of the returnedFuture

Value parameters

f

function that transforms a failure of the receiver into a failure of the returned future

s

function that transforms a successful result of the receiver into a successful result of the returned future

Attributes

Returns

aFuture that will be completed with the transformed value

Source
Future.scala
deftransform[S](f:Try[T]=>Try[S])(implicitexecutor:ExecutionContext):Future[S]

Creates a new Future by applying the specified function to the result of this Future.

Creates a new Future by applying the specified function to the result of this Future. If there is any non-fatal exception thrown when 'f' is applied then that exception will be propagated to the resulting future.

Type parameters

S

the type of the returnedFuture

Value parameters

f

function that transforms the result of this future

Attributes

Returns

aFuture that will be completed with the transformed value

Source
Future.scala
deftransformWith[S](f:Try[T]=>Future[S])(implicitexecutor:ExecutionContext):Future[S]

Creates a new Future by applying the specified function, which produces a Future, to the result of this Future.

Creates a new Future by applying the specified function, which produces a Future, to the result of this Future. If there is any non-fatal exception thrown when 'f' is applied then that exception will be propagated to the resulting future.

Type parameters

S

the type of the returnedFuture

Value parameters

f

function that transforms the result of this future

Attributes

Returns

aFuture that will be completed with the transformed value

Source
Future.scala
finaldefwithFilter(p:T=>Boolean)(implicitexecutor:ExecutionContext):Future[T]

Used by for-comprehensions.

Used by for-comprehensions.

Attributes

Source
Future.scala
defzip[U](that:Future[U]):Future[(T,U)]

Zips the values ofthis andthat future, and creates a new future holding the tuple of their results.

Zips the values ofthis andthat future, and creates a new future holding the tuple of their results.

If either input future fails, the resulting future is failed with the same throwable, without waiting for the other input future to complete.

If the application off throws a non-fatal throwable, the resulting future is failed with that throwable.

Type parameters

U

the type of the otherFuture

Value parameters

that

the otherFuture

Attributes

Returns

aFuture with the results of both futures or the failure of the first of them that failed

Source
Future.scala
defzipWith[U,R](that:Future[U])(f: (T,U)=>R)(implicitexecutor:ExecutionContext):Future[R]

Zips the values ofthis andthat future using a functionf, and creates a new future holding the result.

Zips the values ofthis andthat future using a functionf, and creates a new future holding the result.

If either input future fails, the resulting future is failed with the same throwable, without waiting for the other input future to complete.

If the application off throws a non-fatal throwable, the resulting future is failed with that throwable.

Type parameters

R

the type of the resultingFuture

U

the type of the otherFuture

Value parameters

f

the function to apply to the results ofthis andthat

that

the otherFuture

Attributes

Returns

aFuture with the result of the application off to the results ofthis andthat

Source
Future.scala

Value members

Inherited and Abstract methods

defready(atMost:Duration)(implicitpermit:CanAwait):this.type

Await the "completed" state of thisAwaitable.

Await the "completed" state of thisAwaitable.

This method should not be called directly; useAwait.ready instead.

Value parameters

atMost

maximum wait time, which may be negative (no waiting is done),Duration.Inf for unbounded waiting, or a finite positive duration

Attributes

Returns

thisAwaitable

Throws

InterruptedException if the current thread is interrupted while waiting

TimeoutExceptionif after waiting for the specified time thisAwaitable is still not ready

Inherited from:
Awaitable
Source
Awaitable.scala
defresult(atMost:Duration)(implicitpermit:CanAwait):T

Await and return the result (of typeT) of thisAwaitable.

Await and return the result (of typeT) of thisAwaitable.

This method should not be called directly; useAwait.result instead.

Value parameters

atMost

maximum wait time, which may be negative (no waiting is done),Duration.Inf for unbounded waiting, or a finite positive duration

Attributes

Returns

the result value if theAwaitable is completed within the specific maximum wait time

Throws

InterruptedException if the current thread is interrupted while waiting

TimeoutExceptionif after waiting for the specified time thisAwaitable is still not ready

Inherited from:
Awaitable
Source
Awaitable.scala
In this article
Generated with
Copyright (c) 2002-2025, LAMP/EPFL
Copyright (c) 2002-2025, LAMP/EPFL

[8]ページ先頭

©2009-2025 Movatter.jp