gpt4 book ai didi

scala - Scala 中的错误处理

转载 作者:行者123 更新时间:2023-12-03 08:05:32 24 4
gpt4 key购买 nike

关闭。这个问题是opinion-based .它目前不接受答案。












想改进这个问题?更新问题,以便 editing this post 可以用事实和引用来回答它.

8年前关闭。




Improve this question




假设我有一个函数 foo

def foo(a: A): B = ... 

该函数可能会因以下错误之一而失败: FooError1 , FooError2 , 和 FooError3 .

假设我不想要异常(exception)。所以,我定义了一个基本错误类 FooError ,带有一些派生错误类并返回 Either[FooError, B]来自 foo .

case class FooError(a: A)
case class FooError1(override a: A) extends FooError(a)
case class FooError2(override a: A) extends FooError(a)
case class FooError3(override a: A) extends FooError(a)

def foo(a: A): Either[FooError, B] = ...

是否有意义 ?

看起来每个函数的代码都太多了。可以简化吗?

最佳答案

我认为这值得使用 Try :

  type A = Int
type B = String
class FooError(val a: A) extends Throwable
class FooError1(a: A) extends FooError(a)
class FooError2(a: A) extends FooError(a)
class FooError3(a: A) extends FooError(a)

def foo(a: A): Try[B] = {
val r = scala.util.Random
val i = r.nextInt(20)
Try {
i match {
case it if (1 to 3).contains(i) => throw new FooError1(1)
case it if (4 to 6).contains(i) => throw new FooError2(1)
case it if (7 to 9).contains(i) => throw new FooError3(1)
case _ => "value" + a
}
}
} //> foo: (a: playground.A)scala.util.Try[playground.B]

(1 to 5) foreach { x =>
foo(x) match {
case Success(x) => println(x)
case Failure(t) => // error ignored
} //> value1
//| value4
//| value5
}

事实上,您可以取消所有这些类,只需抛出一个带有错误代码的单一异常类型。
  type A = Int
type B = String
case class FooError(val a: A) extends Throwable

def foo(a: A): Try[B] = {
val r = scala.util.Random
val i = r.nextInt(20)
Try {
i match {
case it if (1 to 3).contains(i) => throw new FooError(1)
case it if (4 to 6).contains(i) => throw new FooError(2)
case it if (7 to 9).contains(i) => throw new FooError(3)
case _ => "value" + a
}
}
} //> foo: (a: play.A)scala.util.Try[play.B]

(1 to 5) foreach { x =>
foo(x) match {
case Success(x) => println(x)
case Failure(t) => t match {
case FooError(code) => println("Error code was "+code)
}
} //> Error code was 1
//| value2
//| Error code was 2
//| value4
//| value5
}

关于scala - Scala 中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21495798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com