15
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-01-29

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
15
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?