Created
October 5, 2011 12:32
-
-
Save t3hnar/1264323 to your computer and use it in GitHub Desktop.
Squeryl Entity
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
package org.squeryl | |
import annotations.Transient | |
import java.lang.reflect.Field | |
/** | |
* @author Yaroslav Klymko | |
*/ | |
trait HasValues { | |
protected def values: List[Any] | |
} | |
trait EquateValues extends Equals with HasValues { | |
override def hashCode() = values.hashCode() | |
override def equals(a: Any) = a match { | |
case that: EquateValues if this.canEqual(that) && that.canEqual(this) => | |
this.values == that.values | |
case _ => false | |
} | |
def canEqual(that: Any): Boolean = that.getClass.isAssignableFrom(getClass) | |
} | |
trait ValuesToString { | |
self: HasValues => | |
override def toString = getClass.getSimpleName + "(" + valuesToString + ")" | |
protected def valuesToString: String = { | |
val fs: List[(String, Any)] = _fields.map(field => field.getName -> field.get(this)) | |
fs.map { | |
case (name, Some(value)) => name + "=" + value | |
case (name, value) => name + "=" + value | |
}.mkString(", ") | |
} | |
@Transient | |
private lazy val _fields: List[Field] = { | |
def get(clazz: Class[_]): List[Field] = if (clazz != classOf[Object]) { | |
get(clazz.getSuperclass) ::: clazz.getDeclaredFields.toList | |
} else Nil | |
val fs: List[(Field, Any)] = get(getClass).map { | |
f => | |
f.setAccessible(true) | |
f -> f.get(this) | |
} | |
values flatMap (value => fs.find(_._2 == value).map(_._1)) | |
} | |
} | |
trait Entity extends HasValues with EquateValues with ValuesToString |
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
class Point(val x: Int, val y: Int) extends Entity { | |
def values = List(x, y) | |
} | |
val x = new Point(1, 2) | |
val x2 = new Point(1, 2) | |
x == x2 // true | |
x.toString //Point(x=1, y=2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment