Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Macro for Adding Mixin to Classes
//SomeTraits.scala
trait Foo {
def someNumbers: List[Int]
def getNumbers : List[Int] = someNumbers
}
trait FilteredFoo extends Foo {
def numberFilter : Int => Boolean
override def getNumbers : List[Int] = super.getNumbers.filter(numberFilter)
}
//SomeMacros.scala
import language.experimental.macros
import scala.reflect.macros.Context
object FilteredFooMacro {
def toFilteredFoo[T <: Foo](instance: T, filter: Int => Boolean): T with FilteredFoo = macro impl[T]
def impl[T: c.WeakTypeTag](c: Context)(instance: c.Expr[T], filter: c.Expr[Int => Boolean]) = {
//????
}
}
//SomeClasses.scala
class A extends Foo {
val someNumbers = List(1,2,3,4)
}
class B extends Foo {
val someNumbers = List(2,4,6,8)
}
//Test.scala
object Test {
def test() {
val a = new A
val b = new B
println(toFilteredFoo(a, x => x % 2 == 0).getNumbers)
println(toFilteredFoo(b, x => x % 2 == 0).getNumbers)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment