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")
    }
  • 相关阅读:
    使用opencv显示视频的方法
    使用visual studio 2012 编译opencv2.4.9
    求前100个斐波那契数
    EXTJs前后台交互 常用哦3种方式
    spring 注解
    程序 人生
    ajaxs
    LNMP源码安装脚本
    系统状态统计和查看
    Shell中的${}、##和%%使用范例
  • 原文地址:https://www.cnblogs.com/shuada/p/5035855.html
Copyright © 2011-2022 走看看