LoginSignup
8
4

More than 5 years have passed since last update.

lift関数いいすね

Last updated at Posted at 2015-05-29

before

ちょっと例が微妙なのだけど、、、
指定されたn番目の値を返す関数。存在するかしないかわからないので戻り値はOptionに。

def foo[A](seq: Seq[A], n: Int): Option[A] = {
  if (!seq.isEmpty && n > 0 && n < seq.size) Some(seq(n))
  else None
}

after

Seq#liftはIntを受け取ってOptionを返す関数。
存在しないindexが与えられればNoneを返してくれるので上記のようなチェックは不要になる。

def foo[A](seq: Seq[A], n: Int): Option[A] = seq.lift(n)

PartialFunction

元はPartialFunctionのlift関数で、これを使うとPartialFunctionを親トレイトであるFunction1に持ち上げる(liftする)事ができる。

val pf: PartialFunction[Int, String] = { case n if n % 2 == 0 => "even!" }
val f: Int => Option[String] = pf.lift

Seqの他にも、PartialFunctionトレイトを持つMapとかStackとかでも使うことが出来る。

8
4
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
8
4