Foreach循环遍历Scala列表?

时间:2018-05-11 17:49:29

标签: scala

我在scala中有一个如下所示的列表:

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

我想使用foreach循环打印出列表中的每个元素。但是当我运行时:

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

我收到以下错误:

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

不确定如何解决此问题!

2 个答案:

答案 0 :(得分:3)

您可以使用嵌套的for - 循环:

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

如果没有for,这也可以写成:

totalQuote.foreach { list =>
  list foreach println
}

甚至

totalQuote foreach (_ foreach println)

如果您只想从每个列表中取出前两个元素,可以将for与模式匹配结合起来,如下所示:

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

for (a :: b :: _ <- totalQuote; x <- List(a, b)) println(x)

答案 1 :(得分:1)

e的类型为List[String],但

val (a,b) = e

仅在e为元组时才有效。试试这个

val a::b::_ = e