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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With