I'm completely new to scala and don't understand why this list isn't coming out right. When I run the program I just get List() as output when I should be getting a list of all the elements of the parameter squared. This should be very simple but the :+ operation is what I've found online and it isn't working.
def Squareall (l: List[Int]): List[Int] ={
var r : List[Int]=List()
for (i<-0 to l.length-1){
r:+ l(i)*l(i)
}
return r
}
The imperative coding style you have in your example is usually avoided in Scala. The for
in Scala is an expression, meaning it results in a value, and thus you can transform your input list directly. To use a for
to transform your input List
you could do something like this:
def squareAll (l: List[Int]): List[Int] = {
for (i <- l) yield i * i
}
If you don't supply the yield
statement a for
results in the Unit
type, which is like void
in Java. This flavor of for
loop is generally for producing side effects , like printing to the screen or writing to a file. If you really just want to transform the data, then there is no need to create and manipulate the resulting List
. (Also method names in Scala are generally "camel cased".)
Most people would probably use the List.map
method instead, though:
def squareAll (l: List[Int]) = l.map((x: Int) => x * x)
or even...
def squareAll (l: List[Int]) = l.map(Math.pow(_, 2.0))
You have to assign the newly created list to r
like this:
r = r:+ l(i)*l(i)
This is because by default List
in Scala is immutable and :+
returns a new list, doesn't update the old one.
Of course there's also a mutable variation of a list scala.collection.mutable.MutableList
. You can use the .++=
method on it to grow the collection.
val mutableList = scala.collection.mutable.MutableList(1, 2)
mutableList.++=(List(3, 4))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.