9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

case classとList/Map/Tupleの相互変換

Posted at
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)

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?