I have a list in scala called l : List[AType] that I want to change to 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.
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.
Is there any more efficient and better way to do this?
Thanks!
In a Scala list, each element need not be of the same data type.
Lists are immutable whereas arrays are mutable in Scala. Lists represents a linked list whereas arrays are flat.
Lists are immutable --- the elements of a list cannot be changed, Lists are recursive (as you will see in the next subsection), Lists are homogeneous: A list is intended to be composed of elements that all have the same type.
In scala we can append elements to the List object in one way only and that is while initializing of the object. This is because the List object is immutable in scala so we cannot change its value once we assign the object.
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. 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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With