(转)Scala中的Some和Option

原文链接

Scala Option[T] is a container for zero or one element of a given type. An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala‘s Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map. The Option type is used frequently in Scala programs and you can compare this to null value available in Java which indicate no value. For example, the get method of java.util.HashMap returns either a value stored in the HashMap, or null if no value was found.

Let‘s say we have a method that retrieves a record from the database based on a primary key:

def findPerson(key: Int): Option[Person]

The method will return Some[Person] if the record is found but None if the record is not found. Let us see a real example:

object Test {
   def main(args: Array[String]) {
      val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")

      println("capitals.get( \"France\" ) : " +  capitals.get( "France" ))
      println("capitals.get( \"India\" ) : " +  capitals.get( "India" ))
   }
}

When the above code is compiled and executed, it produces the following result:

C:/>scalac Test.scala
C:/>scala Test
capitals.get( "France" ) : Some(Paris)
capitals.get( "India" ) : None

C:/>

The most common way to take optional values apart is through a pattern match. For instance:

object Test {
   def main(args: Array[String]) {
      val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")

      println("show(capitals.get( \"Japan\")) : " +
                                          show(capitals.get( "Japan")) )
      println("show(capitals.get( \"India\")) : " +
                                          show(capitals.get( "India")) )
   }

   def show(x: Option[String]) = x match {
      case Some(s) => s
      case None => "?"
   }
}

When the above code is compiled and executed, it produces the following result:

C:/>scalac Test.scala
C:/>scala Test
show(capitals.get( "Japan")) : Tokyo
show(capitals.get( "India")) : ?

C:/>

Using getOrElse() Method:

Following is the example of showing how to use getOrElse() to access a value or a default when no value is present:

object Test {
   def main(args: Array[String]) {
      val a:Option[Int] = Some(5)
      val b:Option[Int] = None 

      println("a.getOrElse(0): " + a.getOrElse(0) )
      println("b.getOrElse(10): " + b.getOrElse(10) )
   }
}

When the above code is compiled and executed, it produces the following result:

C:/>scalac Test.scala
C:/>scala Test
a.getOrElse(0): 5
b.getOrElse(10): 10

C:/>

Using isEmpty() Method:

Following is the example of showing how to use isEmpty() to check if the option is None or not:

object Test {
   def main(args: Array[String]) {
      val a:Option[Int] = Some(5)
      val b:Option[Int] = None 

      println("a.isEmpty: " + a.isEmpty )
      println("b.isEmpty: " + b.isEmpty )
   }
}

When the above code is compiled and executed, it produces the following result:

C:/>scalac Test.scala
C:/>scala Test
a.isEmpty: false
b.isEmpty: true

C:/>

Scala Option Methods:

Following are the important methods which you can use while playing with Options. For a complete list of methods available, please check official documentation of Scala.

SN Methods with Description
1
def get: A

Returns the option‘s value.

2
def isEmpty: Boolean

Returns true if the option is None, false otherwise.

3
def productArity: Int

The size of this product. For a product A(x_1, ..., x_k), returns k

4
def productElement(n: Int): Any

The nth element of this product, 0-based. In other words, for a product A(x_1, ..., x_k), returns x_(n+1) where 0 < n < k.

5
def exists(p: (A) => Boolean): Boolean

Returns true if this option is nonempty and the predicate p returns true when applied to this Option‘s value. Otherwise, returns false.

6
def filter(p: (A) => Boolean): Option[A]

Returns this Option if it is nonempty and applying the predicate p to this Option‘s value returns true. Otherwise, return None.

7
def filterNot(p: (A) => Boolean): Option[A]

Returns this Option if it is nonempty and applying the predicate p to this Option‘s value returns false. Otherwise, return None.

8
def flatMap[B](f: (A) => Option[B]): Option[B]

Returns the result of applying f to this Option‘s value if this Option is nonempty. Returns None if this Option is empty.

9
def foreach[U](f: (A) => U): Unit

Apply the given procedure f to the option‘s value, if it is nonempty. Otherwise, do nothing.

10
def getOrElse[B >: A](default: => B): B

Returns the option‘s value if the option is nonempty, otherwise return the result of evaluating default.

11
def isDefined: Boolean

Returns true if the option is an instance of Some, false otherwise.

12
def iterator: Iterator[A]

Returns a singleton iterator returning the Option‘s value if it is nonempty, or an empty iterator if the option is empty.

13
def map[B](f: (A) => B): Option[B]

Returns a Some containing the result of applying f to this Option‘s value if this Option is nonempty. Otherwise return None.

14
def orElse[B >: A](alternative: => Option[B]): Option[B]

Returns this Option if it is nonempty, otherwise return the result of evaluating alternative.

15
def orNull

Returns the option‘s value if it is nonempty, or null if it is empty.

时间: 2024-10-14 10:47:27

(转)Scala中的Some和Option的相关文章

scala中option、None、some对象

转载:http://www.jianshu.com/p/95896d06a94d 1.option类型避免对象是空值,造成空指针异常. 2.None对象表示null,在没有对象返回时使用,some在有对象值时使用. 避免null使用 大多数语言都有一个特殊的关键字或者对象来表示一个对象引用的是"无",在Java,它是null.在Java 里,null 是一个关键字,不是一个对象,所以对它调用任何方法都是非法的.但是这对语言设计者来说是一件令人疑惑的选择.为什么要在程序员希望返回一个对象

Scala中的空

Scala的有即Any,Scala的无是Null,null,Nil,Nothing,None,Unit.那么这几种空有什么区别呢? 一.Null&null 很多人一辈子都没有走出这个无.Null是一个Trait,你不能创建她它的实例.但是Scala在语言层面上存在一个Null的实例,那就是null.Java中的null意味着引用并没有指向任何对象.但存在一个悖论,一切都是对象,那没有对象是不是也是对象呢?Scala定义了一个类似于对象语义的Null,和一个值语义的null.这样面向对象在空引用的

Scala中的None,Nothing,Null,Nil

在scala中这四个类型名称很类似,作用确实完全不同的. None是一个object,是Option的子类型,定义如下 [java] view plaincopyprint? case object None extends Option[Nothing] { def isEmpty = true def get = throw new NoSuchElementException("None.get") } scala推荐在可能返回空的方法使用Option[X]作为返回类型.如果有值

Scala中的Extractor

Scala中使用unapply方法可以实现三种extractor(另外使用unapplySeq也可以实现extractor) def unapply(object: S): Option[(T1, ..., Tn)] def unapply(object: S): Option[T] def unapply(object: S): Boolean 感觉第三种extractor的使用形式有些奇怪.比如,下面是<快学Scala>中的一个例子: object Name { def unapply(i

Scala中的集合:Iterator、BitSet、Set、Map、Stack、Vector、List、Array

 5.   util包 5.1.     架构 http://www.scala-lang.org/docu/files/collections-api/collections.html The following figure shows all collections in package scala.collection. These are all high-level abstract classes or traits, which generally have mutable

scala中Either的一种使用场景

用scala有一年多了,对于scala中的Option和Try使用的较为频繁,对其应用场景相对熟悉一些.而对于Either,仔细回想一下却发现几乎(完全)没有使用过,其实并不是没有遇到过Either的使用场景,只是遇到的时候不知道能够使用Either来解决此问题. 昨天在网上偶然看到一篇介绍Either的文章,发现有一种场景可以使用Either来解决,具体是这样的: web系统中,Controller层调用service层方法,根据邮箱查询注册的用户User,如果未取到User,则需要知道是什么

第3节 Scala中的模式匹配:1 - 5

7.    模式匹配和样例类 Scala有一个十分强大的模式匹配机制,可以应用到很多场合:如switch语句.类型检查等.并且Scala还提供了样例类,对模式匹配进行了优化,可以快速进行匹配. 7.1.   匹配字符串 package cn.itcast.cases import scala.util.Random object CaseDemo01 extends App{   val arr = Array("hadoop", "zookeeper", &quo

在Scala中免费验证

优锐课带你详细了解如何在Scala中实施免费的monad验证.抽丝剥茧,细说架构那些事! 由于业务数据的复杂性,已经在数据验证上花费了很多精力.在Scala中,提出了使用应用程序进行验证的方法,并被广泛认为是一种有效的方法.受应用验证和免费monad的思想启发,在本文中,我们介绍了一个monadic验证框架,该框架“免费”构建验证.我们将进一步讨论此方法,并通过示例代码演示实现. 在Scala中验证 当检测到错误时,可以以不同的形式找到验证.遇到第一个错误(或异常)时,验证可以立即返回:验证结果

Algebraic Data Type 及其在 Haskell 和 Scala 中的表现

http://songkun.me/2018/07/12/2018-07-12-adt-in-haskell-and-scala/ 函数式编程接触久了以后,我们会发现很多 FP 语言(这里指静态 FP 语言)具有不少类似的语言特性,这非常自然,因为语言特性就那么多,好用.实用的特性更少,这一方面造成了语言之间的同质化,另一方面也减轻了我们语言切换的成本,算是有利也有弊吧. 常见的静态函数式语言有 Haskell.Standard ML.OCaml.Scala 等,它们之间非常类似,共有的特性有: