Created
December 30, 2016 02:10
-
-
Save nightscape/cfedaa92071420dacb0420a186d5dbdd to your computer and use it in GitHub Desktop.
Scala meta macro with annotation and arguments
This file contains hidden or 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
[error] java.lang.IllegalArgumentException: wrong number of arguments | |
[error] @unapply[BlockStmt](Array("getStmts", "getComment", "getOrphanComments")) object BlockStmtCompanion | |
[error] ^ | |
[error] one error found |
This file contains hidden or 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
@unapply[BlockStmt](Array("getStmts", "getComment", "getOrphanComments")) object BlockStmtCompanion |
This file contains hidden or 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.annotation.StaticAnnotation | |
import scala.meta._ | |
class unapply[T](readerMethods: Array[String]) extends scala.annotation.StaticAnnotation { | |
inline def apply(defn: Any): Any = meta { | |
val q"new $_(Array(..${readerMethods: Seq[Term.Arg]}))" = this | |
val unapplyBody = readerMethods.toVector.map(m => Term.Name(m.toString.replaceAll(""""""", ""))).map(a ⇒ q"obj.$a()") | |
val unapply = q"def unapply(obj: T) = Option((..$unapplyBody))" | |
val q"object $name {}" = defn | |
q""" | |
object $name { | |
$unapply | |
}""" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment