LoginSignup
4
3

More than 5 years have passed since last update.

なぜOptionはTraversableOnceをmix-inしてないのにそのように振る舞えるの?

Last updated at Posted at 2016-09-09

はじめに

ListのflatMapはGenTraversableOnceを返す高階関数を期待しているが、以下のようにOption型を返してもコンパイルエラーは起きない。

scala> List(1,2,3,4).flatMap { v => if(v % 2 == 0) Some(v) else None }
res0: List[Int] = List(2, 4)

で、確認すると、

scala> val a: scala.collection.GenTraversableOnce[String] = Option("hello")
a: scala.collection.GenTraversableOnce[String] = List(hello)

代入できる。
リ、リストかぁ(´-`).。oO

TraversableOnceをmix-inしているのかな?

option.png

...していない。

ということは?

Scalaの場合もうアレしかない、Implicit Conversion!

object Option {

  import scala.language.implicitConversions

  /** An implicit conversion that converts an option to an iterable value
   */
  implicit def option2Iterable[A](xo: Option[A]): Iterable[A] = xo.toList

なるほど、toList している。
スッキリ。

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