LUZO
LUZO

Reputation: 1029

How to append elements to list in a for loop : Scala

i want to append list of elements to another list based on a condition. for example : find below code.

package test

object main {
 def main(args: Array[String]): Unit ={
   val a = List(1,2,3,4,5)
   val b= List[Int]()
   for(x <- a){
     if (x>3){
       b:+x
     }
   }
   println(b)
 }
}

when i execute this i am getting empty list.

Upvotes: 2

Views: 18539

Answers (3)

Shankar Shastri
Shankar Shastri

Reputation: 1154

Actually, to make it much generic, you can use tabulate method to prefill your list with required n; Example:

val n = 5
List.tabulate(5)(_ + 1).filter(_ > 3)

Upvotes: 0

marstran
marstran

Reputation: 27961

The List class is immutable in Scala, so you cannot add elements to it. If you really need a mutable list, you can use MutableList.

val a = List(1,2,3,4,5)
val b= MutableList[Int]()
for (x <- a) {
  if (x > 3) {
    b += x
  }
}
println(b)

However, in a functional language like Scala, the best practice is to use immutable collections. Your task can be done very easily with the filter method.

val a = List(1,2,3,4,5)
val b = a.filter(_ > 3)

Upvotes: 9

alexeipab
alexeipab

Reputation: 3619

In Scala List is an immutable collection, you can not add to it, but you can create another collection by applying filter:

val a = List(1,2,3,4,5)
val b = a.filter(x => x > 3)

Upvotes: 2

Related Questions