LoginSignup
5
3

More than 5 years have passed since last update.

FutureとTryの共通メソッド

Posted at

共通メソッド

(implicit executor: ExecutionContext) は省略

共通メソッド Future Try
map map[S](f: (T) ⇒ S): Future[S] map[U](f: (T) ⇒ U): Try[U]
flatMap flatMap[S](f: (T) ⇒ Future[S]): Future[S] flatMap[U](f: (T) ⇒ Try[U]): Try[U]
foreach foreach[U](f: (T) ⇒ U): Unit foreach[U](f: (T) ⇒ U): Unit
failed failed: Future[Throwable] failed: Try[Throwable]
recover recover[U >: T](pf: PartialFunction[Throwable, U]): Future[U] recover[U >: T](f: PartialFunction[Throwable, U]): Try[U]
recoverWith recoverWith[U >: T](pf: PartialFunction[Throwable, Future[U]]): Future[U] recoverWith[U >: T](f: PartialFunction[Throwable, Try[U]]): Try[U]
transform transform[S](s: (T) ⇒ S, f: (Throwable) ⇒ Throwable): Future[S] transform[U](s: (T) ⇒ Try[U], f: (Throwable) ⇒ Try[U]): Try[U]
filter filter(p: (T) ⇒ Boolean): Future[T] filter(p: (T) ⇒ Boolean): Try[T]
withFilter withFilter(p: (T) ⇒ Boolean): Future[T] withFilter(p: (T) ⇒ Boolean): WithFilter

withFilterだけちょっと違うと言えば違うが、まあ同じように使える。

Futureにだけあるメソッド

isCompleted: Boolean

ready(atMost: Duration)(implicit permit: CanAwait): Future.this.type

result(atMost: Duration)(implicit permit: CanAwait): T

value: Option[Try[T]]

onComplete[U](f: (Try[T])  U)(implicit executor: ExecutionContext): Unit

onFailure[U](pf: PartialFunction[Throwable, U])(implicit executor: ExecutionContext): Unit

onSuccess[U](pf: PartialFunction[T, U])(implicit executor: ExecutionContext): Unit

andThen[U](pf: PartialFunction[Try[T], U])(implicit executor: ExecutionContext): Future[T]

collect[S](pf: PartialFunction[T, S])(implicit executor: ExecutionContext): Future[S]

fallbackTo[U >: T](that: Future[U]): Future[U]

mapTo[S](implicit tag: ClassTag[S]): Future[S]

zip[U](that: Future[U]): Future[(T, U)]

collectが意外。Tryにもあっても良さそうなのに。(withFilterとmapで作れるけど)

andThenはfinallyみたいに使ったりする。

mapToはよくわからん。reflection系?

Tryにだけあるメソッド

get: T

isFailure: Boolean

isSuccess: Boolean

getOrElse[U >: T](default:  U): U

orElse[U >: T](default:  Try[U]): Try[U]

toOption: Option[T]

Tryにはfinallyみたいなのは無くて、こうするしかないっぽい。

def doSomething(): Try[A] = {
  val resource = open()

  val t = Try { something(resource) }

  resource.close()

  t
}
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3