zoukankan      html  css  js  c++  java
  • Scala Option 从官方DOC解析

    Represents optional values. Instances of Option are either an instance of scala.Some or the object None.
    Option类代表可选的值。Option的实例要么是Some的实例,要么是None的实例。

    The most idiomatic way to use an scala.Option instance is to treat it as a collection or monad and use map,flatMap, filter, or foreach:

    最符合语言习惯的使用Option的方法是把它看作集合或一元算子。然后使用map, flatmap, filter以及foreach等方法。

    val name: Option[String] = request getParameter "name"
    val upper = name map { _.trim } filter { _.length != 0 } map { _.toUpperCase }
    println(upper getOrElse "")

    Note that this is equivalent to
    这个等价于如下的代码

    val upper = for {
      name <- request getParameter "name"
      trimmed <- Some(name.trim)
      upper <- Some(trimmed.toUpperCase) if trimmed.length != 0
    } yield upper
    println(upper getOrElse "")

    注意这里Scala的For循环与Java的不同之处:Scala的For循环用单个的{}组成,每一行都是一个“A <- B” 的表达式,共有N行。

    前一行<-表达式的左值会被作为下一行<-表达式的右值的参数传递。而且第三行的if表达式所处的位置也是相当的你逆天,新手根本无法接收这样的怪异语法。

    Because of how for comprehension works, if None is returned from request.getParameter, the entire expression results in None
    因为for的特殊使用,如果request getParameter返回了None,那么整个for表达式就返回None

    This allows for sophisticated chaining of scala.Option values without having to check for the existence of a value.
    这样就允许了Option类值的链式传递,而免去了对值的存在性的反复检查操作


    A less-idiomatic way to use scala.Option values is via pattern matching:
    还有一种使用Option类的方法是模式匹配,代码如下:

    val nameMaybe = request getParameter "name"
    nameMaybe match {
      case Some(name) =>
        println(name.trim.toUppercase)
      case None =>
        println("No name value")
    }
  • 相关阅读:
    oracle shrink
    PL/SQL Developer登入时候报ORA-12638: 身份证明检索失败的解决办法
    Oracle11g搭建DataGuard及主备切换方法总结【亲测可用】
    Dataguard主、备库切换方法总结
    CentOS下的Mysql的安装和使用
    在HP-UX上部署oracle客户端
    ORACLE 清理SYSAUX表空间
    第02节-BLE协议各层的形象化理解
    第01节-生活中的实例_医院的结构
    仿照手机写一个WIFI的操作程序
  • 原文地址:https://www.cnblogs.com/shuada/p/5035855.html
Copyright © 2011-2022 走看看