在 Scala 中,是否有一种简单的方法可以将案例类转换为元组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8087958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Scala, is there an easy way to convert a case class into a tuple?
提问by Douglas
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.
我真正想要的是一种轻松制作按字典顺序排序的案例类的方法。我可以通过导入 scala.math.Ordering.Implicits._ 来实现元组的目标,瞧,我的元组为它们定义了一个排序。但是 scala.math.Ordering 中的隐式通常不适用于案例类。
回答by S-C
How about calling unapply().getin the companion object?
调用unapply().get伴生对象怎么样?
case class Foo(foo: String, bar: Int)
val (str, in) = Foo.unapply(Foo("test", 123)).get
// str: String = test
// in: Int = 123
回答by James Moore
Shapelesswill do this for you.
Shapeless将为您做到这一点。
import shapeless._
import shapeless.syntax.std.product._
case class Fnord(a: Int, b: String)
List(Fnord(1, "z - last"), Fnord(1, "a - first")).sortBy(_.productElements.tupled)
Gets
获取
res0: List[Fnord] = List(Fnord(1,a - first), Fnord(1,z - last))
productElements turns a case class into a Shapeless HList:
productElements 将 case 类转换为 Shapeless HList:
scala> Fnord(1, "z - last").productElements
res1: Int :: String :: shapeless.HNil = 1 :: z - last :: HNil
And HLists are converted to tuples with #tupled:
并且 HLists 被转换为带有 #tupled 的元组:
scala> Fnord(1, "z - last").productElements.tupled
res2: (Int, String) = (1,z - last)
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.
性能可能会很糟糕,因为您一直在转换。您可能会将所有内容转换为元组形式,对其进行排序,然后使用类似(Fnord.apply _).tupled.
回答by Dean Wampler
You might try extending the ProductNtrait, for N=1-22, which TupleNextends. 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.
您可以尝试扩展ProductN特征,对于 N=1-22,它会TupleN扩展。它会给你很多元组语义的,如_1,_2等方法。根据您使用类型的方式,这可能就足够了,而无需创建实际的元组。
回答by AnthonyShipman
Came across this old thread while attempting to do this same thing. I eventually settled on this solution:
在尝试做同样的事情时遇到了这个旧线程。我最终确定了这个解决方案:
case class Foo(foo: String, bar: Int)
val testFoo = Foo("a string", 1)
val (str, in) = testFoo match { case Foo(f, b) => (f, b) }

