Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Scala how do you reference index in List of Serializable?

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")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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")
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading