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!
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)
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
您可以简单地使用以下命令打印列表中的每个元素
totalQuote.flatten.foreach{x => println(x)}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.