Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert values of a case class into Seq?

Tags:

scala

I am new to Scala and I am having to provide values extracted from an object/case class into a Seq. I was wondering whether there would be any generic way of extracting values of an object into Seq of those values in order?

Convert the following:

case class Customer(name: Option[String], age: Int)
val customer = Customer(Some("John"), 24)

into:

val values = Seq("John", 24)
like image 944
lbrahim Avatar asked Jun 06 '20 07:06

lbrahim


1 Answers

case class extends Product class and it provides such method:

case class Person(age:Int, name:String, lastName:Option[String])

def seq(p:Product) = p.productIterator.toList

val s:Seq[Any] = seq(Person(100, "Albert", Some("Einstain")))
println(s) //List(100, Albert, Some(Einstain))

https://scalafiddle.io/sf/oD7qk8u/0

Problem is that you will get untyped list/array from it. Most of the time it is not optimal way of doing things, and you should always prefer statically typed solutions.

like image 114
Scalway Avatar answered Sep 30 '22 02:09

Scalway