Help us understand the problem. What is going on with this article?

Scala 2.10でOptionに新しく追加されたメソッド

More than 3 years have passed since last update.

fold

@inline final def fold[B](ifEmpty: => B)(f: A => B): B =
  if (isEmpty) ifEmpty else f(this.get)

opt.fold(value)(f)

opt map f getOrElse valueとやっていることは同じ

flatten

def flatten[B](implicit ev: A <:< Option[B]): Option[B] =
  if (isEmpty) None else ev(this.get)

Option(Option(1)).flatten // => Some(1)

要素がOptionの場合、それを平坦化する

implicit ev: A <:< Option[B]
を書くことで要素がOptionであることを保障する
なのでOption(1).flattenのようなコードはエラーになる

nonEmpty

final def nonEmpty = isDefined

isDefinedはisEmptyを反転させたもの。

contains

final def contains[A1 >: A](elem: A1): Boolean =
  !isEmpty && this.get == elem

Option(1).contains(1)                   // => true
Option("string").contains("strin")      // => false
Option[String](null).contains("string") // => false

引数とOptionの要素が同じかチェックする。
Noneの場合、getは呼ばれないので例外は投げられない
あとこのメソッド2.10じゃなくて2.11から追加されたっぽい

forall

@inline final def forall(p: A => Boolean): Boolean =
  isEmpty || p(this.get)

Option("string").forall(_.length > 5)     // => true
Option("string").forall(_.length < 5) // => false
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away