简体   繁体   English

在scala中更改列表类型的最佳方法

[英]Best way to change list type in scala

I have a list in scala called l : List[AType] that I want to change to list[String]. 我在scala中有一个名为l:List [AType]的列表,我想将其更改为list [String]。

This may sound like a very dirty, inefficient approach, but I'm not quite sure of the best way to do this. 这可能听起来像一个非常肮脏,低效的方法,但我不太确定这样做的最好方法。 My code was: 我的代码是:

var result = new Array[String]("a","b")
l foreach { case a => result = result :+ (a.toString().toUpperCase()); }
result toList

I'm not sure if this is where my mistake is, because it's not giving me anything, it's not even printing anything even if I put a print statement inside the loop. 我不确定这是不是我的错误,因为它没有给我任何东西,即使我在循环中放置一个print语句也不打印任何东西。

So I decided to change this to a more imperative way: 所以我决定将其更改为更为迫切的方式:

for(i <- 0 to l.length) {
    result.update(i, l(i).toString)
}

This time I see things that I want to see when printing inside the loop, but at the end the program crashed with an IndexOutOfBound error. 这次我看到在循环内打印时我想看到的东西,但最后程序因IndexOutOfBound错误而崩溃。

Is there any more efficient and better way to do this? 有没有更有效和更好的方法来做到这一点?

Thanks! 谢谢!

Take a look at the map function. 看看地图功能。 For example, 例如,

scala> List("Some", "Strings").map(_.toUpperCase)
res2: List[java.lang.String] = List(SOME, STRINGS)

or 要么

scala> List("Some", "Strings").map(_.length)
res0: List[Int] = List(4, 7)

Just a remark on the for loop. 只是对for循环的评论。 Here are two correct ways of doing that loop: 以下是执行该循环的两种正确方法:

// Using "until" instead of "to": a until b == a to (b - 1)
for(i <- 0 until l.length) {
    result.update(i, l(i).toString)
}

// Using "indices" to get the range for you
for(i <- l.indices) {
    result.update(i, l(i).toString)
}
 def f(s:String) = s.toCharArray // or output something else of any type 
 val l = List("123", "234", "345")
 l.map(f)

你有没有尝试过理解?

val result=for(elem <- l) yield elem.toString().toUpperCase();

How about 怎么样

for(i <- 0 to l.length-1) {
    result.update(i, l(i).toString)
}

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

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