0

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?

4
  • also asked at users.scala-lang.org/t/how-to-handle-error-or-return-value/8609 Commented Jun 27, 2022 at 16:30
  • Okey, so you found a throwable, you print it, and now what? Does the program stop? Commented Jun 27, 2022 at 16:32
  • @LuisMiguelMejíaSuárez no the program is calling the playAgain function with the following signature: def playAgain: ZIO[Console, Throwable, Has[Any]] Commented Jun 28, 2022 at 6:07
  • I don't understand exactly how to fits the code you provided, but anyways. It seems you should rather lift that Either into the ZIO Commented Jun 28, 2022 at 12:57

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, but another silly question: what can I use as a default value and how to implement that? :)
@helloworld it depends on your logic and what are you trying to achieve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.