Search code examples
scalaexceptiontry-catchreturn-type

Scala "Try" return type and exception handling


I am a newbie for Scala and now am trying to complete an exercise. How can I return an InvalidCartException while the function return type is Try[Price]

//Success: return the calculated price
//Failure: InvalidCartException

def calculateCartPrice(cart:Cart): Try[Price] = {
    if(isCartValid(cart)) {
        //Calculations happen here
        return Try(Price(totalPrice));
    }
}

def isCartValid(cart: Cart): Boolean = {
    //THIS WORKS FINE
}

Thank you for the help


Solution

  • If you mean "how to make the Try contain an exception", then use the Failure() like below:

    def calculateCartPrice(cart:Cart): Try[Price] = {
        if(isCartValid(cart)) {
            //Calculations happen here
            Success(Price(totalPrice));
        } else {
            Failure(new InvalidCartException())
        }
    }
    

    Then, given a Try you can use getOrElse to get the value of success or throw the exception.