Created
May 27, 2012 15:02
-
-
Save okapies/2814608 to your computer and use it in GitHub Desktop.
How to implement case class manually. (for Scala 2.9.2 final)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ScalaRuntime.*
s are no longer used by the compiller.See also: