问题描述
有没有人有使用 scala.util.control.Exception
版本 2.12.0 (2.8.0 版), ?我正在努力从类型中弄清楚.
Does anybody have good examples of using scala.util.control.Exception
version 2.12.0 (version 2.8.0), ? I am struggling to figure it out from the types.
推荐答案
确实 - 我也觉得这很令人困惑!这是一个问题,我有一些属性可能是可解析的日期:
Indeed - I also find it pretty confusing! Here's a problem where I have some property which may be a parseable date:
def parse(s: String) : Date = new SimpleDateFormat("yyyy-MM-dd").parse(s)
def parseDate = parse(System.getProperty("foo.bar"))
type PE = ParseException
import scala.util.control.Exception._
val d1 = try {
parseDate
} catch {
case e: PE => new Date
}
将其转换为函数形式:
val date =
catching(classOf[PE]) either parseDate fold (_ => new Date, identity(_) )
在上面的代码中,把catch(t)或者expr
变成一个Either[T, E]
,其中T
是throwable 的类型和 E
是表达式的类型.然后可以通过 fold
将其转换为特定值.
In the above code, turns catching(t) either expr
will result in an Either[T, E]
where T
is the throwable's type and E
is the expression's type. This can then be converted to a specific value via a fold
.
或者另一个版本:
val date =
handling(classOf[PE]) by (_ => new Date) apply parseDate
这可能更清楚一些 - 以下是等效的:
This is perhaps a little clearer - the following are equivalent:
handling(t) by g apply f
try { f } catch { case _ : t => g }
这篇关于使用 scala.util.control.Exception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!