In Scala - Converting a case class List into a List of tuples

风流意气都作罢 提交于 2021-02-07 17:24:47

问题


i have a case class

case class table(a: String, b: Option[String])

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 

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

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

so my question would be -> how can I use unapply on every tuple of a List?

thank in advance


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)

with the error:

Cannot prove that models.table <:<(T,U)

and it would work for a (String, Option[String]) list


回答1:


You want to convert every element of a list giving another list. You need foreach's cousin, map:

Try:

 list1.map(table.unapply).flatten

which is a better way of writing:

 list1.map( tbl => table.unapply(tbl) ).flatten

Another way would be

 list1.map(table.unapply(_).get)

Which is shorthand for

 list1.map( tbl => table.unapply(tbl).get )

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)


来源:https://stackoverflow.com/questions/15113269/in-scala-converting-a-case-class-list-into-a-list-of-tuples

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!