简体   繁体   English

如何在Scala上分配值选项[List [String]]

[英]How Assign Value Option[List[String]] on Scala

This question is about assign parameter value Option[List[String]] in Scala. 这个问题是关于在Scala中分配参数值Option[List[String]]

My code: 我的代码:

def mapListString(pList : Option[List[String]]) = pList match {
    case None => "-"
    case Some(cocok) => cocok
    case _ => "?"
}

A List is immutable in Scala. List在Scala中是不可变的。 You cannot append/prepand values to the same list. 您不能将值追加/预填充到同一列表中。 If you do, you'll be given a new List containing the added values. 如果这样做,将为您提供一个包含添加值的新List

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. Scala支持不变性,并为您提供方便的语法来使用它们。 However, mutable lists do exist in Scala, you can find one, eg, in scala.collection.mutable.MutableList 但是,可变列表确实存在于Scala中,您可以在scala.collection.mutable.MutableList找到一个可变列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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