case-class

What is the difference between Scala's case class and class?

↘锁芯ラ 提交于 2019-11-26 11:57:47
I searched in Google to find the differences between a case class and a class . Everyone mentions that when you want to do pattern matching on the class, use case class. Otherwise use classes and also mentioning some extra perks like equals and hash code overriding. But are these the only reasons why one should use a case class instead of class? I guess there should be some very important reason for this feature in Scala. What is the explanation or is there a resource to learn more about the Scala case classes from? Case classes can be seen as plain and immutable data-holding objects that

Easy idiomatic way to define Ordering for a simple case class

会有一股神秘感。 提交于 2019-11-26 11:47:23
问题 I have a list of simple scala case class instances and I want to print them in predictable, lexicographical order using list.sorted , but receive \"No implicit Ordering defined for ...\". Is there exist an implicit that provides lexicographical ordering for case classes? Is there simple idiomatic way to mix-in lexicographical ordering into case class? scala> case class A(tag:String, load:Int) scala> val l = List(A(\"words\",50),A(\"article\",2),A(\"lines\",7)) scala> l.sorted.foreach(println)

Case class to map in Scala

徘徊边缘 提交于 2019-11-26 08:45:28
问题 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\") into a mapping of some kind, e.g. getCCParams(x) returns \"param1\" -> \"hello\", \"param2\" -> \"world\" 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

Case class equality in Apache Spark

…衆ロ難τιáo~ 提交于 2019-11-26 02:13:59
问题 Why does pattern matching in Spark not work the same as in Scala? See example below... function f() tries to pattern match on class, which works in the Scala REPL but fails in Spark and results in all \"???\". f2() is a workaround that gets the desired result in Spark using .isInstanceOf() , but I understand that to be bad form in Scala. Any help on pattern matching the correct way in this scenario in Spark would be greatly appreciated. abstract class a extends Serializable {val a: Int} case

Cleaner way to update nested structures

我怕爱的太早我们不能终老 提交于 2019-11-26 01:48:23
问题 Say I have got following two case class es: case class Address(street: String, city: String, state: String, zipCode: Int) case class Person(firstName: String, lastName: String, address: Address) and the following instance of Person class: val raj = Person(\"Raj\", \"Shekhar\", Address(\"M Gandhi Marg\", \"Mumbai\", \"Maharashtra\", 411342)) Now if I want to update zipCode of raj then I will have to do: val updatedRaj = raj.copy(address = raj.address.copy(zipCode = raj.address.zipCode + 1))