Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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].

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!

like image 832
Enrico Susatyo Avatar asked Aug 04 '10 23:08

Enrico Susatyo


People also ask

Can list have different data types in Scala?

In a Scala list, each element need not be of the same data type.

Are lists mutable Scala?

Lists are immutable whereas arrays are mutable in Scala. Lists represents a linked list whereas arrays are flat.

Is list homogeneous in Scala?

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.

Can we add elements to list in Scala?

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.


2 Answers

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)
like image 159
sluukkonen Avatar answered Oct 18 '22 04:10

sluukkonen


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)
}
like image 21
Daniel C. Sobral Avatar answered Oct 18 '22 04:10

Daniel C. Sobral