0

This question is about assign parameter value Option[List[String]] in Scala.

My code:

def mapListString(pList : Option[List[String]]) = pList match {
    case None => "-"
    case Some(cocok) => cocok
    case _ => "?"
}
dbc
  • 104,963
  • 20
  • 228
  • 340
  • You cannot. Such parameter are immutable in Scala. BTW the way of doing in Scala is most of the time based on immutability. I suggest you have a look at the related docs. – cchantep Mar 16 '16 at 09:50
  • What do you want to "assign" to what? Show a "pseudocode" illustrating what you are trying to do, even if it does not compile. – Dima Mar 16 '16 at 11:02
  • Cchantep : i already did Dima : to manipulation value. – Christian Yonathan S. Mar 17 '16 at 02:42

1 Answers1

0

A List is immutable in Scala. You cannot append/prepand values to the same list. If you do, you'll be given a new List containing the added values.

One possible implementation would look like this:

scala> :paste
// Entering paste mode (ctrl-D to finish)

  val pList: Option[List[String]] = Some(List("hello"))
  val result = pList match {
    case None => Some(List("-"))
    case Some(cocok) => Some("x" :: cocok)
  }

// Exiting paste mode, now interpreting.

pList: Option[List[String]] = Some(List(hello))
result: Some[List[String]] = Some(List(hello, x))

Scala favors immutability and provides you convienient syntax to work with them. However, mutable lists do exist in Scala, you can find one, e.g, in scala.collection.mutable.MutableList

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • That's about list, but the parameter as `Option` is immutable without an alternative mutable type. – cchantep Mar 16 '16 at 10:40
  • You're right, but I'm not sure that's what the OP meant. I think he wanted to append to the same list, regardless of it being wrapped in a new option or not. – Yuval Itzchakov Mar 16 '16 at 10:59