gpt4 book ai didi

scala - 如何将scala匹配表达式的中间结果存储到列表中?

转载 作者:行者123 更新时间:2023-12-01 07:23:17 24 4
gpt4 key购买 nike

我有一个整数列表作为输入,我想将 scala 匹配表达式中每个比较的中间结果存储到 ListBuffer 中。我怎样才能做到这一点?
下面是我写的代码。目前我只能存储上次比较的结果,而不是中间的结果。

import scala.collection.mutable.ListBuffer
object HelloWorld {
def main(args: Array[String]) {
var stor = ListBuffer[String]()
val inpLst = List(1, 2, 2, 2, 1)
for (i <- inpLst) {
stor = i match {
case 1 => "ok"
case 2 => "notok"
}
}
println(stor)
}
}

这是我想要的输出。
opList = List("ok","notok","notok',"notok","ok")

最佳答案

@Mario Galic 的回答是解决问题的好方法,如果您仍然坚持以自己的方式写作,下面是解决方法。

import scala.collection.mutable.ListBuffer

val inpLst = List(1,2,2,2,1)
val stor = ListBuffer.empty[String]

for (i <- inpLst) {
val str = i match {
case 1 => "ok"
case 2 => "notOk"
}
stor += str
}

println(stor)

这输出如下:
ListBuffer(ok, notOk, notOk, notOk, ok)

关于scala - 如何将scala匹配表达式的中间结果存储到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59030017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com