Skip to content

Instantly share code, notes, and snippets.

@MarounMaroun
Created November 20, 2017 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarounMaroun/e8f621d2d476642352ccbc9cb9eae235 to your computer and use it in GitHub Desktop.
Save MarounMaroun/e8f621d2d476642352ccbc9cb9eae235 to your computer and use it in GitHub Desktop.
Difference between "case class" and "class" in Scala
/**
* Case classes define a factory method for creating instances:
* - lines 24-25 don't have the "new" keyword.
*
* Case classes generate implementations of toString, hashCode and quals:
* - see output in lines 24-27
*
* Much more differences, like immutability and generation of companion object.
*
* Note that in order to run the snippet below, use "scala" directly, don't attempt to compile with "scalac".
*/
// case class
case class StudentCase(name: String, age: Int)
// class
class Student(name: String, age: Int)
var student1 = new Student("test", 10)
var student2 = new Student("test", 10)
// hash codes are different
println(student1.hashCode)
println(student2.hashCode)
// so result is false
println(student1 == student2)
var studentCase1 = StudentCase("test", 10)
var studentCase2 = StudentCase("test", 10)
// hash codes are the same
println(studentCase1.hashCode)
println(studentCase2.hashCode)
// so result is true
println(studentCase1 == studentCase2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment