繁体   English   中英

Scala:什么是opt关键字?

[英]Scala: What is opt keyword?

以下代码中的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

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

上面的代码等效于以下代码,我们在其中使用. 调用方法opt和以下either一方法的语法:

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

它不是关键字 ,而是从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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM