Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, is there an easy way to convert a case class into a tuple?

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.

like image 307
Douglas Avatar asked Nov 10 '11 23:11

Douglas


People also ask

What is the benefit of case class in scala?

While all of these features are great benefits to functional programming, as they write in the book, Programming in Scala (Odersky, Spoon, and Venners), “the biggest advantage of case classes is that they support pattern matching.” Pattern matching is a major feature of FP languages, and Scala's case classes provide a ...

Can scala case class have methods?

Case Classes You can construct them without using new. case classes automatically have equality and nice toString methods based on the constructor arguments. case classes can have methods just like normal classes.

Is scala case class immutable?

A Scala Case Class is like a regular class, except it is good for modeling immutable data. It also serves useful in pattern matching, such a class has a default apply() method which handles object construction. A scala case class also has all vals, which means they are immutable.

What is difference between Case class and case object in scala?

A case class can take arguments, so each instance of that case class can be different based on the values of it's arguments. A case object on the other hand does not take args in the constructor, so there can only be one instance of it (a singleton, like a regular scala object is).


1 Answers

How about calling unapply().get in the companion object?

case class Foo(foo: String, bar: Int)  val (str, in) = Foo.unapply(Foo("test", 123)).get // str: String = test // in: Int = 123 
like image 52
S-C Avatar answered Oct 19 '22 12:10

S-C