0

Given the following recursive function that returns Try[Int], I get a compilation error saying

type mismatch; found : scala.util.Try[Int] required: Int

But the function returns Try[Int], what is wrong? I need the function to throw an error if Try results in Failure.

   def getInt(i: Int): Try[Int] = Try {
          if (i == 0)
              i
          else {
              val j = i - 1
              getInt(j)   // <-- error is thrown in this line
          }
   }
0

2 Answers 2

3

You have a Try inside a Try now.

Try (hah!) this:

def getInt(i: Int): Try[Int] = 
      if (i == 0)
          Success(0)
      else
          getInt(i-1)  
Sign up to request clarification or add additional context in comments.

Comments

1

method getInt return Try[Int] so you are writing it like this:

Try { if (i == 0) return integer else return Try[Int] }

To fix this you have to do it this way:

  def getInt(i: Int): Try[Int] = 
    if (i == 0)
      Success(i)
    else {
      val j = i - 1
      getInt(j)   // <-- error is thrown in this line
    }

as Success extends Try this will work

Comments

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.