Scala“尝试”返回类型和异常处理

发布于 2025-01-30 18:59:23 字数 449 浏览 4 评论 0 原文

我是 scala 的新手,现在正在尝试完成练习。 我如何返回 无效

//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
}

当功能返回类型为时,

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烙印 2025-02-06 18:59:23

如果您的意思是“如何制作尝试包含异常” ,则使用 fafer()如下:

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

然后,给定尝试您可以使用 getorelse 获得成功的价值或抛出异常。

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.

人疚 2025-02-06 18:59:23

尝试将为您捕获异常,因此将可以将异常的代码放入其中。例如

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

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

,如果您拥有的是尝试,并且想在拥有 Fafer 的情况下抛出异常,则可以使用模式匹配来执行此操作:

val result = divideByOne(0)

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

新手scala scala of scala 有很多有用的Scala的人(i在我学习时发现它非常宝贵。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文