Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
16
Help us understand the problem. What is going on with this article?
@bububu

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

More than 5 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
16
Help us understand the problem. What is going on with this article?
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
bububu

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
16
Help us understand the problem. What is going on with this article?