0

I have a list in scala that looks like the following:

val totalQuote: List[List[String]] = List(List("a","b","c"),List("1","2","3"),List("d","e","f"),List("4","5","6"))

I want to print out every element in the list using a foreach loop. However when I run this:

totalQuote.foreach{ e =>
      val(a,b) = e
      println(a)
    }

I get the following error:

Error:(17, 10) constructor cannot be instantiated to expected type;
 found   : (T1, T2)
 required: List[String]
      val(a,b) = e

Not sure how to resolve this!

3 Answers 3

3

You could use nested for-loops:

for {
  list <- totalQuote
  character <- list
} println(character)

Without for, this could also be written as:

totalQuote.foreach { list =>
  list foreach println
}

or even

totalQuote foreach (_ foreach println)

If you want to take only the first two elements out of every list, you could combine for with pattern-matching as follows:

for (a :: b :: _ <- totalQuote) { 
  println(a)
  println(b) 
}

or

for (a :: b :: _ <- totalQuote; x <- List(a, b)) println(x)
Sign up to request clarification or add additional context in comments.

Comments

1

The type of e is List[String] but

val (a,b) = e

only works if e is a tuple. Try this

val a::b::_ = e

Comments

0

You can simply use the following to print each element of the list

  totalQuote.flatten.foreach{x => println(x)}

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.