我在 scala 中有一个名为 l : List[AType] 的列表,我想将其更改为 list[String]。
这听起来像是一种非常肮脏、低效的方法,但我不太确定最好的方法。我的代码是:
var result = new Array[String]("a","b")
l foreach { case a => result = result :+ (a.toString().toUpperCase()); }
result toList
我不确定这是否是我的错误所在,因为它没有给我任何东西,即使我在循环中放入打印语句,它甚至没有打印任何内容。
所以我决定将其更改为更命令式的方式:
for(i <- 0 to l.length) {
result.update(i, l(i).toString)
}
这次我在循环内打印时看到了我想看到的东西,但最后程序因 IndexOutOfBound 错误而崩溃。
有没有更有效、更好的方法来做到这一点?
谢谢!
最佳答案
看看 map 功能。例如,
scala> List("Some", "Strings").map(_.toUpperCase)
res2: List[java.lang.String] = List(SOME, STRINGS)
或
scala> List("Some", "Strings").map(_.length)
res0: List[Int] = List(4, 7)
关于arrays - 在 scala 中更改列表类型的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3410717/