Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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

like image 208
RohbRoy Avatar asked Dec 20 '22 09:12

RohbRoy


1 Answers

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)
like image 69
Faiz Avatar answered Feb 15 '23 13:02

Faiz