-
-
Save fedesilva/5751764 to your computer and use it in GitHub Desktop.
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
package macros | |
import language.experimental.macros | |
import scala.reflect.macros.Macro | |
object Macros { | |
def swap(a: _, b: _) = macro Impl.swap | |
} | |
trait Impl extends Macro { | |
import c.universe._ | |
import c.universe.Flag._ | |
def swap(a: c.Tree, b: c.Tree): c.Tree = { | |
val tmp = TermName(c.freshName("tmp")) | |
q"{ var $tmp = $a; $a = $b; $b = $tmp }" | |
/* | |
// without quasiquotes | |
Block( | |
List( | |
ValDef(Modifiers(MUTABLE), tmp, TypeTree(), a), | |
Assign(a, b), | |
Assign(b, Ident(tmp)) | |
), | |
Literal(Constant(())) | |
) | |
*/ | |
} | |
} |
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 macros.Macros.swap | |
object Test extends App { | |
var a = 10 | |
var b = 5 | |
println((a, b)) | |
swap(a, b) | |
println((a, b)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment