Home > Back-end >  I am not able to append list using loops in scala
I am not able to append list using loops in scala

Time:10-21

object LoopList extends App {
  var even_list = List()
  var odd_list = List()

  for (i <- Range(1,10)) {
    if ((i % 2) == 0) {
      even_list = even_list :  i
    } else {
      odd_list = odd_list :  i
    }
  }

  println(even_list)
}

I am trying to create 2 simple lists for odd and even, although i know lists are immutable but i tried tuples as well. Please suggest a way to new solution using for loop only.

CodePudding user response:

From what I can tell the problem is that at the point of their declaration the compiler doesn't have enough information to determine the type of the items in the list. As such, it determines that the list is a List[Nothing] and the compiler tells you that you are trying to add an Int but that it needs Nothing.

To solve the problem, you can add a simple type annotation as in the following example:

var even_list: List[Int] = List()
var odd_list: List[Int] = List()

for (i <- Range(1, 10)) {
  if ((i % 2) == 0) {
    even_list = even_list :  i
  } else {
    odd_list = odd_list :  i
  }
}

println(even_list)

You can play around with this code here on Scastie.

As suggested in a comment, you are definitely encouraged to experiment with the Collection API of the Scala standard library, which provides you with very powerful constructs to create your programs in a way that is compact and readable, as in the example provided above to construct the lists with a single line of code:

val (evens, odds) = List.range(1, 10).partition(i => (i % 2) == 0)

CodePudding user response:

By the way, appending an element is an extremely slow List operation. If it possible, it is better to use reverse order to construct a List:

    var even_list: List[Int] = Nil
    var odd_list: List[Int] = Nil

    for (i <- 9 to 1 by -1) {
      if ((i % 2) == 0) {
        even_list = i :: even_list
      } else {
        odd_list = i :: odd_list
      }
    }

    println(even_list)
    println(odd_list)

Or use another suitable collection with following conversion to a List.

  • Related