简体   繁体   English

来自Map的案例类

[英]case class from Map

I'm trying to implement (de)serialization from Scala case classes to Maps (field_name -> field_value). 我正在尝试从Scala案例类到map(field_name - > field_value)实现(de)序列化。 The problem is I don't know how to create a function, that would take a case class type and a map, instantiate, populate and return it. 问题是我不知道如何创建一个函数,它将采用case类类型和map,实例化,填充并返回它。 I've seen this done in some JSON libraries, but I don't get the code. 我在一些JSON库中看到过这种情况,但我没有得到代码。

Doing this for a particular case class is trivial: 对特定案例类执行此操作非常简单:

scala> :paste
// Entering paste mode (ctrl-D to finish)

case class Foo(x: Int, y: Double, z: String) {
  def toMap = Map('x -> x, 'y -> y, 'z -> z)
}
object Foo {
  def apply(vals: Map[Symbol, Any]): Foo = Foo(vals('x).asInstanceOf[Int], vals('y).asInstanceOf[Double], vals('z).asInstanceOf[String])
}

// Exiting paste mode, now interpreting.

defined class Foo
defined module Foo

scala> Foo(Map('x -> 1, 'y -> 2.0, 'z -> "wibble"))
res0: Foo = Foo(1,2.0,wibble)

scala> res0.toMap
res1: scala.collection.immutable.Map[Symbol,Any] = Map('x -> 1, 'y -> 2.0, 'z -> wibble)

But I'm guessing that you want to create something that works for any case class, where you don't necessarily know what the names of the values are? 但我猜你想要创建适用于任何案例类的东西,你不一定知道这些值的名称是什么?

In which case, you're going to have to take a look at reflection (added in Scala 2.10.0): 在这种情况下,您将不得不看一下反射(在Scala 2.10.0中添加):

http://docs.scala-lang.org/overviews/reflection/overview.html http://docs.scala-lang.org/overviews/reflection/overview.html

You can use reflection to iterate over the members of a class, find out what their names are and then create your map. 您可以使用反射来迭代类的成员,找出它们的名称,然后创建地图。 For example: 例如:

scala> import reflect.runtime.universe._
import reflect.runtime.universe._

scala> typeOf[Foo].members filter { m => m.isMethod && m.asMethod.isStable }
res2: Iterable[reflect.runtime.universe.Symbol] = SynchronizedOps(value z, value y, value x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM