Created
May 31, 2014 18:48
-
-
Save Arneball/392ea620693697414b24 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
/** | |
* Created by arneball on 2014-05-31. | |
*/ | |
object LazyTest extends App { | |
val n = new LazyTest | |
try { | |
println(n.lazyIntInDaHouse) | |
} catch { case t: Throwable => } | |
println(n.lazyIntInDaHouse) | |
} | |
class LazyTest { | |
var failedOnce = false | |
@lazzy val lazyIntInDaHouse: Int = { | |
println("Initiating") | |
if(!failedOnce) { | |
failedOnce = true | |
??? | |
} | |
1488 | |
} | |
} |
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 scala.annotation.StaticAnnotation | |
import language.experimental.macros | |
import scala.reflect.macros.whitebox.Context | |
/** | |
* Created by arneball on 2014-05-31. | |
*/ | |
object LazyMacro { | |
def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = { | |
import c.universe._ | |
annottees.map{ _.tree }.head match { | |
case q"$mods val $name: $ret = $b" => | |
val nmeDefined = TermName(s"${name}Defined") | |
val nmeVal = TermName(s"${name}Value") | |
val lazyCompute = TermName(s"lazyCompute$name") | |
c.Expr[Any]{ | |
q""" | |
private[this] var $nmeDefined = false | |
private[this] var $nmeVal: $ret = _ | |
private def $lazyCompute: $ret = { | |
$nmeVal = $b | |
$nmeDefined = true | |
$nmeVal | |
} | |
$mods def $name: $ret = { | |
if($nmeDefined) $nmeVal else $lazyCompute | |
} | |
""" | |
} | |
case _ => c.abort(c.enclosingPosition, "Only vals can be annotated") | |
} | |
} | |
} | |
class lazzy extends StaticAnnotation { | |
def macroTransform(annottees: Any*) = macro LazyMacro.impl | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment