在 Scala 中 - 将案例类列表转换为元组列表 [英] In Scala - Converting a case class List into a List of tuples
问题描述
我有一个案例类
case class table(a: String, b: Option[String])
我有一个这种类型的列表 - 让我们称之为 list1
and i have a list of that type - lets call it list1
val list1: List[table] = tabele.get() // just filling the list from an SQL
现在我想将表"的列表更改为一个简单的 (String,Option[String]) 列表我已经在这个板上找到的是如何将案例类转换为元组像这样:
now I want to change the list of "table" into a simple list of (String,Option[String]) What i allready found on this board was how to convert a case class into a tuple like that:
case class table(a:String, b:Int)
val (str, in) = table.unapply(table("test", 123)).get()
但我不知道如何在列表上使用它:(我用 foreach 尝试了一些类似的东西:
But i don't know how to use this on a List :( I tried something with foreach like:
val list2: List[(String, Option[String])] = Nil
list1.foreach( x => list2 :: table.unapply(x).get())
'error (String,Option[String]) does not take parameters
所以我的问题是 -> 如何在 List 的每个元组上使用 unapply?
so my question would be -> how can I use unapply on every tuple of a List?
提前致谢
PS:我实际上想更改列表的类型,因为我想在该列表上使用.toMap"- 喜欢:
PS: I actually want to change the type of the list because I want to use ".toMap" on that list - like:
val map1 = list1.toMap.withDefaultValue(None)
错误:
Cannot prove that models.table <:<(T,U)
它适用于 (String, Option[String]) 列表
and it would work for a (String, Option[String]) list
推荐答案
您想转换列表中的每个元素并给出另一个列表.你需要foreach
的表亲,map
:
You want to convert every element of a list giving another list. You need foreach
's cousin, map
:
试试:
list1.map(table.unapply).flatten
这是一种更好的写作方式:
which is a better way of writing:
list1.map( tbl => table.unapply(tbl) ).flatten
另一种方式是
list1.map(table.unapply(_).get)
这是什么的简写
list1.map( tbl => table.unapply(tbl).get )
并且只是使用 for
加入一个版本:(这说明了 unapply
在 for
推导式中的使用方式)
And just to throw in a version using for
: (which is illustrative of how unapply
is used under the hood in for
comprehensions)
for (table(s,ms) <- list1) yield (s, ms)
这篇关于在 Scala 中 - 将案例类列表转换为元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!