Home > Enterprise >  Scala "Try" return type and exception handling
Scala "Try" return type and exception handling

Time:05-19

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

CodePudding user response:

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.

CodePudding user response:

Try will catch the exception for you, so put the code that can throw the exception in there. For example

def divideOneBy(x: Int): Try[Int] = Try { 1 / x}

divideOneBy(0) // Failure(java.lang.ArithmeticException: / by zero)

If what you have is a Try and you want to throw the exception when you have a Failure, then you can use pattern matching to do that:

val result = divideByOne(0)

result match {
    case Failure(exception) => throw exception
    case Success(_) => // What happens here?
}

The Neophyte's Guide to Scala has lots of useful information for people new to Scala (I found it invaluable when I was learning).

  • Related