AJm
AJm

Reputation: 1023

Scala : adding to Scala List

I am trying to append to a List[String] based on a condition But List shows empty

Here is the Simple code :

object Mytester{

  def main(args : Array[String]): Unit = {
    val columnNames = List("t01354", "t03345", "t11858", "t1801566", "t180387685", "t015434")
    //println(columnNames)

    val prim = List[String]()

    for(i <- columnNames) {
      if(i.startsWith("t01"))
        println("Printing i : " + i)
        i :: prim :: Nil
    }

    println(prim)
  }
}

Output :

Printing i : t01354
Printing i : t015434
List()

Process finished with exit code 0

Upvotes: 0

Views: 147

Answers (3)

jwvh
jwvh

Reputation: 51271

This line, i :: prim :: Nil, creates a new List[] but that new List is not saved (i.e. assigned to a variable) so it is thrown away. prim is never changed, and it can't be because it is a val.

If you want a new List of only those elements that meet a certain condition then filter the list.

val prim: List[String] = columnNames.filter(_.startsWith("t01"))
// prim: List[String] = List(t01354, t015434)

Upvotes: 3

Arnon Rotem-Gal-Oz
Arnon Rotem-Gal-Oz

Reputation: 25929

In addition to what jwvh explained. Note that in Scala you'd usually do what you want as

val prim = columnNames.filter(_.startsWith("t01"))

Upvotes: 0

prayagupadhyay
prayagupadhyay

Reputation: 31252

1) why can't I add to List?

List is immutable, you have to mutable List (called ListBuffer)

definition

scala> val list = scala.collection.mutable.ListBuffer[String]()
list: scala.collection.mutable.ListBuffer[String] = ListBuffer()

add elements

scala> list+="prayagupd"
res3: list.type = ListBuffer(prayagupd)

scala> list+="urayagppd"
res4: list.type = ListBuffer(prayagupd, urayagppd)

print list

scala> list
res5: scala.collection.mutable.ListBuffer[String] = ListBuffer(prayagupd, urayagppd)

2. Filtering a list in scala?

Also, in your case the best approach to solve the problem would be to use List#filter, no need to use for loop.

scala> val columnNames = List("t01354", "t03345", "t11858", "t1801566", "t180387685", "t015434")
columnNames: List[String] = List(t01354, t03345, t11858, t1801566, t180387685, t015434)

scala> val columnsStartingWithT01 = columnNames.filter(_.startsWith("t01"))
columnsStartingWithT01: List[String] = List(t01354, t015434)

Related resources

Add element to a list In Scala

filter a List according to multiple contains

Upvotes: 1

Related Questions