Scala:什么是opt关键字?

时间:2016-10-28 15:11:46

标签: scala

以下代码中的opt关键字是什么?

import scala.util.control.Exception._
import java.net._

val s = "http://www.scala-lang.org/"
val x1 = catching(classOf[MalformedURLException]) opt new URL(s)
val x2 = catching(classOf[MalformedURLException], classOf[NullPointerException]) either new URL(s)

http://www.scala-lang.org/api/current/scala/util/control/Exception $。HTML

2 个答案:

答案 0 :(得分:7)

它不是关键字,它是Catch[T]中定义的方法,其结果类型为catching()。请参阅http://www.scala-lang.org/api/current/index.html#scala.util.control.Exception$$Catch@opt[U%3E:T](body:=%3EU):Option[U]

上的文档

以上代码与以下代码等效,我们使用.语法调用方法opteither

val s = "http://www.scala-lang.org/"
val x1 = catching(classOf[MalformedURLException]).opt(new URL(s))
val x2 = catching(classOf[MalformedURLException], classOf[NullPointerException]).either(new URL(s))

答案 1 :(得分:4)

它不是关键字,它是从scala.util.control.Exception._导入的方法,这里是它的定义和Scaladoc:

/** Apply this catch logic to the supplied body, mapping the result
 *  into `Option[T]` - `None` if any exception was caught, `Some(T)` otherwise.
 */
def opt[U >: T](body: => U): Option[U] = toOption(Some(body))