Skip to content

Instantly share code, notes, and snippets.

Created May 27, 2012 15:02
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save okapies/2814608 to your computer and use it in GitHub Desktop.
Save okapies/2814608 to your computer and use it in GitHub Desktop.
How to implement case class manually. (for Scala 2.9.2 final)
import scala.runtime.ScalaRunTime
* A sample code to implement a customized case class manually (for Scala 2.9.2 final).
* Id has two properties: name and displayName. 'displayName' has default value that
* is same value as 'name'.
class Id private ( // make primary constructor not to be accessible. (standard case class can do)
val name: String,
val displayName: String,
) extends Product with Serializable { // inherits from Product and Serializable.
// implement copy method manually.
def copy(
name: String =,
displayName: String = this.displayName) =
Id.apply(name, displayName)
// Product (used by Scala runtime)
override def productPrefix = classOf[Id].getSimpleName
def productArity = 2
def productElement(n: Int): Any = n match {
case 0 =>
case 1 => this.displayName
case _ => throw new IndexOutOfBoundsException(n.toString)
def canEqual(that: Any) = that.isInstanceOf[Id]
// NOTE: Scaladoc of ScalaRunTime says that "All these methods should be considered
// outside the API and subject to change or removal without notice."
override def equals(that: Any) = ScalaRunTime._equals(this, that)
// Object (AnyRef)
override def hashCode() = ScalaRunTime._hashCode(this)
override def toString = ScalaRunTime._toString(this)
object Id {
// exclusive factory method
def apply(
name: String,
displayName: String = null) = displayName match {
case null => new Id(name, name)
case _ => new Id(name, displayName)
// for pattern matching
def unapply(id: Id) = Some((, id.displayName))