gpt4 book ai didi

scala - 在Scala中使用模式匹配在Val初始化时捕获MatchError?

转载 作者:行者123 更新时间:2023-12-04 22:07:15 25 4
gpt4 key购买 nike

在使用模式匹配分配值时,捕获MatchError的最佳方法(确定,清晰,惯用)是什么?

例子:

val a :: b :: Nil = List(1,2,3) // throws scala.MatchError

到目前为止,我发现的最好方法是:
val a :: b :: Nil = try {
val a1 :: b1 :: Nil = List(1,2,3)
List(a1, b1)
catch { case e:MatchError => // handle error here }

有没有惯用的方法来做到这一点?

最佳答案

稍微改进Kim的解决方案:

val a :: b :: Nil = List(1, 2, 3) match {
case x @ _ :: _ :: Nil => x
case _ => //handle error
}

如果您可以提供有关如何处理错误的更多信息,我们可以为您提供更好的解决方案。

关于scala - 在Scala中使用模式匹配在Val初始化时捕获MatchError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8908707/

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