scala中的option、option[T]、Right和Left

前提:当我们设置一个数据库时,一个名字(String)对应一个年龄(Int)

当我输入一个名字的时候来查询这个人的年龄的时候,如果输入一个没有在数据库中的人名,那么该如何返回?


返回0?很明显是不可以的

抛出异常?但是丢失值不可能认定为异常。


java的解决方法:

将方法标记为返回  java.lang.Integer,那么這样就可以放查询的时候返回null值

scala的解决方法------option类型或option[T]

我们来看看option到底是什么:

scala中的option就相当于一个容器,这个容易里面是0(None)或者1(Some),对于Some可以看作是一个List的大集合

sealed abstract classOption[+A] extends Product with Serializable
Represents optional values. Instances of  Option  are either an instance of  scala.Some  or the object  None .

它是一个具有两个子类 Some[T] 和 None 的泛型类,用来表示 是否有“无值” 的情况

用实验来说明一些问题:

val info = Map("peter"->"18", "linus"->"30", "andrew"->"40","curry"->null)


scala> info get "peter"
res0: Option[String] = Some(18)

scala> info get "legotime"
res1: Option[String] = None

scala> info get "curry"
res2: Option[String] = Some(null)

Some表示在map中有这个人,而None表示的是没有这个人,那么我们接着get具体的信息
scala>  info get "peter" get
warning: there were 1 feature warning(s); re-run with -feature for details
res4: String = 18

scala> info get "curry" get
warning: there were 1 feature warning(s); re-run with -feature for details
res5: String = null

scala>  info get "legotime" get
/*报错信息*/

我们接着来看看其他函数:

1 、getOrElse

final def getOrElse[B >: A](default: ⇒ B): B
Returns the option's value if the option is nonempty, otherwise return the result of evaluating default.
default  the default expression.
scala>  (info get "legotime") getOrElse "Oops"
res7: String = Oops

scala>  (info get "peter") getOrElse "Oops"
res8: String = 18

分析:getOrElse后面的表达就是当前面是None的时候,那么就会执行后面的表达式


2、nonEmpty

final def orElse[B >: A](alternative: ⇒ Option[B]): Option[B]
Returns this scala.Option if it is nonempty, otherwise return the result of evaluating alternative.
alternative the alternative expression.

scala>  (info get "peter") nonEmpty
res9: Boolean = true
分析: nonEmpty就是判断前面时候是Some还是None
3、 orNull

scala>  (info get "legotime") orNull
res10: String = null


Option[T]的一些操作如:for

首先定义个函数:

def printMapElement(x:Option[String]){
      for (a <- x){
     println(a) 
     }
}
scala> printMapElement(info get "peter")
18

scala> printMapElement(info get "legotime")

scala>

分析:如果是None,那么就不会去执行a



Left和Right

Either/Left/Right和Option/Some/None很像下面是,两者之间的比较:

Either 和Option一样.
Right 和 Some一样
Left  和None一样, 但是你可以包含一个用来描述问题的字符串

Updata:Scala 2.10有介绍过 Try, Success, and Failure。他们提供了比Either/Left/Right 更好方法

下面通过代码来说明:

object EitherLeftRightExample extends App {

  /**
    * A simple method to demonstrate how to declare that a method returns an Either,
    * and code that returns a Left or Right.
    */
  def divideXByY(x: Int, y: Int): Either[String, Int] = {
    if (y == 0) Left("Dude, can't divide by 0")
    else Right(x / y)
  }

  // a few different ways to use Either, Left, and Right
  println(divideXByY(1, 0))
  println(divideXByY(1, 1))
  divideXByY(1, 0) match {
    case Left(s) => println("Answer: " + s)
    case Right(i) => println("Answer: " + i)
  }
  divideXByY(1, 1) match {
    case Left(s) => println("Answer: " + s)
    case Right(i) => println("Answer: " + i)
      //Left(Dude, can't divide by 0)
      //Right(1)
      //Answer: Dude, can't divide by 0
      //Answer: 1
  }


}

分析:调用divideXByY方法,返回的是Either[String, Int],左边的String是Left()内部包含的信息。

右边的Int是Right()内部包含的信息。






参考文献:

scala cookbook






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值