Advertisement
Guest User

Untitled

a guest
Apr 18th, 2014
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.24 KB | None | 0 0
  1. object CaseClassMacro {
  2.   def implementation(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
  3.     import c.universe._
  4.  
  5.     // lekérjük az annotált objektumokat egyenként
  6.     annottees.map(_.tree).toList match {
  7.       // mintaillesztéssel kiválogatjuk azokat az eseteket,
  8.       // amikor egy osztályt jelöltünk meg vele
  9.       case q"class $name(..$params) extends ..$parents { ..$body }" :: Nil => {
  10.         val termName : TermName = name.toTermName
  11.         val parameterNames = params.map(param => param.name)
  12.         val parameterTypes = params.map((param : ValDef) => param.tpt)
  13.  
  14.         val selections = parameterNames.map((param: TermName) => Select(Ident(newTermName("obj")), param))
  15.  
  16.         val tree = q"""
  17.          class $name protected (..$params) extends ..$parents { ..$body }
  18.  
  19.          object $termName {
  20.            def apply(..$params) = new $name(..$parameterNames)
  21.            def unapply(obj: $name) : Option[(..$parameterTypes)] = Some(
  22.              (..$selections)
  23.            )
  24.          }
  25.        """
  26.         println(show(tree))
  27.         c.Expr[Any](tree)
  28.       }
  29.       case _ => {
  30.         c.error(c.enclosingPosition, "Unsupported expression!")
  31.         c.Expr[Any](EmptyTree)
  32.       }
  33.     }
  34.   }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement