【问题标题】:Scala: What is opt keyword?Scala:什么是 opt 关键字?
【发布时间】:2016-10-28 15:11:45
【问题描述】:

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

【问题讨论】:

    标签: scala


    【解决方案1】:

    不是关键字,是方法,定义在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))
    

    【讨论】:

    • 几乎完全相同的时间发布了两个相当相似的答案,都被赞成 - 礼仪是什么 - 我们现在该怎么办? :))
    • AFAIK Stack Overflow 不允许一个人接受同一个问题的两个答案,因此没有公平的解决方案。最不公平的做法是随机选择接受哪一个,然后投票赞成另一个……
    • 我有时看到的另一个“策略”是接受信誉最低的用户的回答。
    • 感谢您的帮助!
    【解决方案2】:

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

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2012-03-15
    • 2014-11-28
    • 2012-09-20
    • 2014-03-16
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多