scala> case class Foo(i: Int, s: String)
defined class Foo
scala> val f = Foo(1, "bar")
f: Foo = Foo(1,bar)
// case class -> List
scala> val l = f.productIterator.toList
l: List[Any] = List(1, bar)
// List -> case class
scala> Foo.getClass.getMethods.find(_.getName == "apply").get.invoke(Foo, l.map(_.asInstanceOf[AnyRef]):_*).asInstanceOf[Foo]
res1: Foo = Foo(1,bar)
// case class -> Map
scala> val m = f.getClass.getDeclaredFields.map(_.getName).zip(f.productIterator.toList).toMap
m: scala.collection.immutable.Map[java.lang.String,Any] = Map(i -> 1, s -> bar)
// Map -> case class
scala> Foo.getClass.getMethods.find(_.getName == "apply").get.invoke(Foo, m.values.toList.map(_.asInstanceOf[AnyRef]):_*).asInstanceOf[Foo]
res2: Foo = Foo(1,bar)
// case class -> Tuple
scala> val t = Foo.unapply(f).get
t: (Int, String) = (1,bar)
// Tuple -> case class
scala> Foo.tupled(t)
res3: Foo = Foo(1,bar)
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme