Skip to content

Instantly share code, notes, and snippets.

@Arneball
Last active August 29, 2015 14:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Arneball/a222b99a7b689bde9585 to your computer and use it in GitHub Desktop.
Save Arneball/a222b99a7b689bde9585 to your computer and use it in GitHub Desktop.
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