在 Scala 中映射的案例类 [英] Case class to map in Scala

查看:41
本文介绍了在 Scala 中映射的案例类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种很好的方法可以转换 Scala case class 实例,例如

Is there a nice way I can convert a Scala case class instance, e.g.

case class MyClass(param1: String, param2: String)
val x = MyClass("hello", "world")

转换成某种映射,例如

getCCParams(x) returns "param1" -> "hello", "param2" -> "world"

适用于任何案例类,而不仅仅是预定义的.我发现您可以通过编写一个询问底层 Product 类的方法来提取案例类名称,例如

Which works for any case class, not just predefined ones. I've found you can pull the case class name out by writing a method that interrogates the underlying Product class, e.g.

def getCCName(caseobj: Product) = caseobj.productPrefix 
getCCName(x) returns "MyClass"

所以我正在寻找类似的解决方案,但用于案例类字段.我想一个解决方案可能必须使用 Java 反射,但如果 case 类的底层实现发生变化,我不想写一些可能会在 Scala 的未来版本中中断的东西.

So I'm looking for a similar solution but for the case class fields. I'd imagine a solution might have to use Java reflection, but I'd hate to write something that might break in a future release of Scala if the underlying implementation of case classes changes.

目前我正在 Scala 服务器上工作,并使用 case 类定义协议及其所有消息和异常,因为它们非常漂亮、简洁.但我随后需要将它们转换为 Java 映射,以通过消息传递层发送以供任何客户端实现使用.我当前的实现只是分别为每个案例类定义了一个翻译,但最好能找到一个通用的解决方案.

Currently I'm working on a Scala server and defining the protocol and all its messages and exceptions using case classes, as they are such a beautiful, concise construct for this. But I then need to translate them into a Java map to send over the messaging layer for any client implementation to use. My current implementation just defines a translation for each case class separately, but it would be nice to find a generalised solution.

推荐答案

这应该有效:

def getCCParams(cc: AnyRef) =
  cc.getClass.getDeclaredFields.foldLeft(Map.empty[String, Any]) { (a, f) =>
    f.setAccessible(true)
    a + (f.getName -> f.get(cc))
  }

这篇关于在 Scala 中映射的案例类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆