Created
February 27, 2014 22:08
-
-
Save lambdaknight/9260629 to your computer and use it in GitHub Desktop.
Macro for Adding Mixin to Classes
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
//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