0

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(.....)).

3
  • Can you show us what have you done ? Commented Jul 8, 2021 at 14:34
  • So supposing the Option was a Some then you want to prepend all the elements returned by myFunction if it was a None then nothing should be added, right? Commented Jul 8, 2021 at 15:33
  • Yes, thats what I need. Commented Jul 8, 2021 at 15:34

1 Answer 1

2

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]] = ???
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.