简体   繁体   中英

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

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM