0

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

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Actually i :: prim :: Nil creates List[Any].
1

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.