scalaにおけるoption,option[T],Right,Left

6773 ワード

前提:データベースを設定すると、名前(String)は年齢(Int)に対応します.
名前を入力したときにその人の年齢を調べに来たとき、データベースにいない人の名前を入力したら、どうやって返しますか?
0を返しますか?明らかにできない
異常を投げ出す?ただし、損失値が異常とは認められない.
JAvaの解決方法:
メソッドをjavaを返すようにマークします.lang.Integer、これでクエリーを置くときにnull値を返すことができます
scalaの解決策------optionタイプまたはoption[T]
optionが何なのか見てみましょう
scalaの中のoptionは1つの容器に相当して、これは簡単に中は0(None)あるいは1(Some)で、Someに対して1つの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
.
2つのサブクラス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/Neneは次のように似ています.両者の比較は次のとおりです.
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