3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ScalaでFutureの処理結果をEither型に格納してみる

Posted at

概要

Scalaの便利な機能として、「Future」を使って、http通信などの非同期処理が簡単にかけることが挙げられます。
Futureですが内部処理でExceptionが発生した場合、どうハンドリングをすべきかという点を意識する必要があります。【Scala】Future と未来のセカイの記事にもある通り、通常と異常で取得する値の型が異なるわけです。
例えばFutureの結果を次処理でそのまま使いたい場合、使えるのがEither型だろうということで今回はFutureの結果をEither型で格納するサンプルを作成してみました。

サンプルコード

例外が発生した場合、recoverメソッドを使ってEitherのLeftに値を設定するようにします。なお、recoverについては[Scala] Future#recoverを使って例外処理するにて解説されています。
以下のコードは与えられた値が1だったら2倍してRightに設定し、それ以外だったらエラーメッセージをLeftに設定します。

FutureTest.scala
  def testRecover(param: Int) = {
    val sample1 = Future {
      if (param == 1) { 1 } else { throw new IllegalArgumentException("error!")}
    }
    val test = Await.result(
      sample1.map{f => Right(f * 2)}
        recover {case e: IllegalArgumentException => Left(e.getMessage)}
      , 1 minute)
    println(test)
  }
3
0
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?