Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Macro annotation extension method
class ext extends StaticAnnotation {
def macroTransform(annottees: Any*) = macro extension.impl
}
object extension {
def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
import c.universe._
annottees.map{ _.tree }.head match {
case q"def $name[..$tp](...$params): $ret = $b" =>
val Seq(Seq(thiz, rest @ _*), rest2 @ _*) = params
val rr = rest +: rest2
val term = c.freshName()
val term2 = TypeName(term)
c.Expr[Any]{
q"""
implicit class $term2[..$tp]($thiz) extends AnyVal {
def $name(...$rr): $ret = $b
}
"""
}
case that =>
println(that)
c.abort(c.enclosingPosition, that.toString)
}
}
}
import scala.collection.generic.CanBuildFrom
/**
* Created by arneball on 2014-05-26.
*/
object ExtensionMethod extends App with Integral.ExtraImplicits {
@ext def add(thiz: Int, that: Int) = thiz + that
println{
5 add 5
}
@ext def unary_!(thiz: String) = thiz.reverse
println{
!"Hello world"
}
type CB[CC[_], From, Elem] = CanBuildFrom[CC[From], Elem, CC[Elem]]
@ext def collPart[T, U, SEQ[x] <: Seq[x]](thiz: SEQ[T], fun: PartialFunction[T, U])(implicit cbf: CB[SEQ, T, T], cb2: CB[SEQ, T, U]): (SEQ[U], SEQ[T]) = {
val trues = cb2()
val falses = cbf()
thiz.foreach{ e =>
if(fun.isDefinedAt(e)) trues += fun(e) else falses += e
}
trues.result() -> falses.result()
}
val (x1, x2) = Vector(1, 2, 3, 4, 5).collPart{ case 2 => "Shit" }
println(x1)
println(x2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.