【问题标题】:How Assign Value Option[List[String]] on Scala如何在 Scala 上赋值 Option[List[String]]
【发布时间】:2016-07-02 02:34:59
【问题描述】:

这个问题是关于在Scala中分配参数值Option[List[String]]

我的代码:

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

【问题讨论】:

  • 你不能。这样的参数在 Scala 中是不可变的。顺便说一句,Scala 的做法大部分时间都是基于不变性的。我建议您查看相关文档。
  • 你想“分配”什么?显示一个“伪代码”来说明你正在尝试做什么,即使它没有编译。
  • Cchantep : 我已经做了 Dima : 来操纵价值。

标签: string list scala option


【解决方案1】:

List 在 Scala 中是不可变的。您不能将值附加/预置到同一个列表中。如果这样做,您将获得一个新的List,其中包含添加的值。

一种可能的实现如下所示:

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 支持不变性,并为您提供方便的语法来使用它们。但是,Scala 中确实存在可变列表,您可以在 scala.collection.mutable.MutableList 中找到一个,例如

【讨论】:

  • 这是关于列表的,但是Option 的参数是不可变的,没有替代的可变类型。
  • 你是对的,但我不确定这就是 OP 的意思。我认为他想附加到同一个列表中,无论它是否包含在新选项中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 2021-01-13
  • 2020-01-11
  • 1970-01-01
  • 2017-01-03
  • 2023-01-29
  • 1970-01-01
相关资源
最近更新 更多