Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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 = this.name,
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 => this.id
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.name, id.displayName))
}