在Scala中,有没有一种简单的方法将案例类转换为元组?
有没有一种简单的方法将案例类转换为元组?
当然,我可以轻松编写样板代码来执行此操作,但我的意思是没有样板。
我真正追求的是一种轻松地按字典顺序排列案例类的方法。我可以通过导入 scala.math.Ordering.Implicits._ 来实现元组的目标,瞧,我的元组已经为它们定义了排序。但 scala.math.Ordering 中的隐含内容通常不适用于案例类。
Is there an easy way to convert a case class into a tuple?
I can, of course, easily write boilerplate code to do this, but I mean without the boilerplate.
What I'm really after is a way to easily make a case class lexicographically Ordered. I can achieve the goal for tuples by importing scala.math.Ordering.Implicits._, and voila, my tuples have an Ordering defined for them. But the implicits in scala.math.Ordering don't work for case classes in general.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在伴生对象中调用
unapply().get
怎么样?How about calling
unapply().get
in the companion object?Shapeless 会为你做到这一点。
获取
productElements 将案例类转换为Shapeless HList:
并且HList 使用#tupled 转换为元组:
性能可能很糟糕,因为您不断进行转换。您可能会将所有内容都转换为元组形式,对其进行排序,然后使用诸如
(Fnord.apply _).tupled
之类的内容将其转换回来。Shapeless will do this for you.
Gets
productElements turns a case class into a Shapeless HList:
And HLists are converted to tuples with #tupled:
Performance is likely to be horrible, since you're constantly converting. You'd probably convert everything to the tupled form, sort that, then convert it back using something like
(Fnord.apply _).tupled
.Scala 3 对案例类和元组之间的转换提供一流的支持:
Scala 3 has first class support for conversions between case classes and tuples:
在尝试做同样的事情时遇到了这个旧线程。我最终选择了这个解决方案:
Came across this old thread while attempting to do this same thing. I eventually settled on this solution:
您可以尝试扩展
ProductN
特征,对于 N=1-22,TupleN
扩展了该特征。它会给你很多元组语义,比如_1
、_2
等方法。根据您使用类型的方式,这可能就足够了,而无需创建实际的元组。You might try extending the
ProductN
trait, for N=1-22, whichTupleN
extends. It will give you a lot of Tuple semantics, like the_1
,_2
, etc. methods. Depending on you how you use your types, this might be sufficient without creating an actual Tuple.好吧,这不是一个通用的解决方案,但遗憾的是,对我来说最优雅的方法是在案例类本身中添加
toTuple
。至少在我们迁移到 Scala 3 之前是这样。Well, it's not a general solution, but sadly the most elegant way for me is to add the
toTuple
inside the case class itself. At least before we migrate to Scala 3.特别是对于 Scala 3,这是我一直在使用的解决方案(基于此 文章):
Specifically for Scala 3, here's a solution I've been using (based on a code snippet from this article):