Search code examples
listscalaprepend

Prepend to a list causes error: value :: is not a member of Option[List[String]]


x variable is an option list:

val x = Option(List("listX"))

Now trying to prepend something to list:

"listY"::x

causes error below:

error: value :: is not a member of Option[List[String]]

How can I prepend to an option list?


Solution

  • This is because type of x is inferred from the value Option(List("listX")) is Option[List[String]] and you would like to prepend value in List inside Option, so instead you need to do: x.map(value => "listY" :: value). Hope this helps!