Home > Software engineering >  In Scala how do you reference index in List of Serializable?
In Scala how do you reference index in List of Serializable?

Time:10-29

I'm new to Scala, actually learning it. I'm trying to combine multiple Lists and print a table by passing the list into a function. However when I try referencing values by index I get the error

Serializable does not take parameters

println("%3s%3s%3s\n".formatted(elm(0),elm(1),elm(2))) val list1 = List("1","2","3") val list2 = List("1","1","5")

var newLst = List[Serializable]()

newLst : = list1
newLst : = list2

def display_table(a:List[Serializable]){

  println("%3s%3s%3s\n".formatted("A","B","C"))
  for (elm <- a){
      println("%3s%3s%3s\n".formatted(elm(0),elm(1),elm(2)))
  }
}

display_table(newLst)

How what is the proper way of combining Lists of Lists and being able to iterate through them and reference them by index?

CodePudding user response:

The specific answer is that you don't have a List of Lists, you have a List of Serializables and you can't index into a Serializable.

But you don't need to index into the List to get the leading elements, just use match:

val list1 = List("1", "2", "3")
val list2 = List("1", "1", "5")
val newLst = List(list1, list2)

def display_table(a: List[List[String]]) = {
  println("  A  B  C")
  for (elm <- a) {
    elm match {
      case a :: b :: c :: _ =>
        println(f"$a%3s$b%3s$c%3s")
      case _ =>
        println("Not enough elements")
    }
  }
}

display_table(newLst)

Or use foreach directly rather than for:

def display_table(a: List[List[String]]) = {
  println("  A  B  C")
  a.foreach{
    case a :: b :: c :: _ =>
      println(f"$a%3s$b%3s$c%3s")
    case _ =>
      println("Not enough elements")
  }
}
  • Related