Last active
December 21, 2015 21:19
-
-
Save seraphr/6367633 to your computer and use it in GitHub Desktop.
forとパターンマッチ あとはcollect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
case class Data(opt: Option[String]) | |
val tList = List(Data(None), Data(Some("hoge")), Data(None), Data(Some("fuga")), Data(Some("piyo"))) | |
for(Data(Some(str)) <- tList) yield str | |
tList.collect { | |
case Data(Some(str)) => str | |
} | |
// Dataの中に複数のOptionがある場合 | |
case class Data2(opt: Option[String]*) | |
val tList2 = List(Data2(None, Some("foo")), Data2(Some("hoge"), Some("bar")), Data2(None), Data2(Some("fuga")), Data2(Some("piyo"))) | |
tList2.flatMap { | |
case Data2(seq @ _*) => seq.flatten | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
scala> for(Data(Some(str)) <- tList) yield str | |
res26: List[String] = List(hoge, fuga, piyo) | |
scala> tList.collect { | |
| case Data(Some(str)) => str | |
| } | |
res27: List[String] = List(hoge, fuga, piyo) | |
scala> tList2.flatMap { | |
| case Data2(seq @ _*) => seq.flatten | |
| } | |
res28: List[String] = List(foo, hoge, bar, fuga, piyo) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment