Advertisement
Guest User

Untitled

a guest
Sep 1st, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. import java.time.Instant
  2.  
  3. /**
  4. * Created by aloise on 01.09.16.
  5. */
  6. case class User( name:String, email:String, password:String, createdAt:Instant )
  7.  
  8. class WithId[T <: Product ]( val id: Int, val value: T ) extends Product {
  9.  
  10.  
  11. override def productElement(n: Int): Any = n match {
  12. case 0 => id
  13. case _ => value.productElement( n - 1 )
  14. }
  15.  
  16. override def productArity: Int = 1 + value.productArity
  17.  
  18. override def canEqual(that: Any): Boolean = {
  19. that match {
  20. case value1: this.type =>
  21. value1.canEqual(this) && ( value1.id == this.id )
  22. case _ =>
  23. false
  24. }
  25. }
  26. }
  27.  
  28.  
  29. object WithIdHelper {
  30.  
  31.  
  32. class WithIdRichHelper[T<:Product](value:T) {
  33.  
  34. def withId( id: Int ): WithId[T] = {
  35. new WithId[T](id, value)
  36. }
  37. }
  38.  
  39. implicit def toProduct[T<:Product]( withIdClass:WithId[T] ):T = {
  40. withIdClass.value
  41. }
  42.  
  43. implicit def liftToWithId[T<:Product](value:T):WithIdRichHelper[T] = {
  44. new WithIdRichHelper[T](value)
  45. }
  46.  
  47. }
  48.  
  49. object CaseClassTests {
  50. def main(args: Array[String]): Unit = {
  51.  
  52. import WithIdHelper.{ toProduct, liftToWithId }
  53.  
  54. val user = User("aloise","test", "password", Instant.now())
  55.  
  56. val userWithId = user withId 5
  57.  
  58. println( userWithId.id, userWithId.name, userWithId.email )
  59.  
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement