简体   繁体   中英

Scala: Creating Options from Seq/Tuple and add to a Sequence

Edit:

Suppose I have a Seq:

Seq(Some("Earth"),Some("Mars"))

I need to add few more elements at start of this sequence. Values to be added are generated based on an Option value. So I try to do as:

 val o = ....//Option calculated here
 Seq(o.map(myFunction(_)),"Earth","Mars")

 def myFunction(s: String) = s match {
     case "x" => Seq(Some("Jupiter"), Some("Venus"))
     case "y"  => Seq(Some("PLuto"), Some("Mercury"))
 }

But map would give me Some(Seq(.....)).

For this kind of problem I recommend checking the Scaladoc and following a technique called type-tetris .

You need this:

def prependIfDefined(data: Option[A], previousElements: Seq[Option[B]]): Seq[Option[B]] =
  data.fold(ifEmpty = Seq.empty[Option[B]])(getNewData) ++ previousElements

def getNewData(a: A): Seq[Option[B]] = ???

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM