helloworld
helloworld

Reputation: 137

How to handle error or return value with a method

I want to test, if the value is a Throwable, if it is, I want to print out an error message.

If the value is not a Throwable, I want to return it.

I have this code, which gives me following error message, when Im hovering over the "value" which sould be returned in the last line:

Found: (value : Either[Throwable, A]) Required: A )

def throwAndPlayAgainOrGet[A](value: Either[Throwable, A]): A =
{
    if(value.isLeft) println("error: " + value) + playAgain
    value
}

My Question:

how can I do that?

Upvotes: 0

Views: 121

Answers (1)

Guru Stron
Guru Stron

Reputation: 142123

You can use pattern matching for this:

def throwAndPlayAgainOrGet[A](value: Either[Throwable, A]): A = value match {
  case Left(err) => {
    println(err)
    someDefaultAValue // or throw err
  }
  case Right(v) => v
}

Upvotes: 2

Related Questions