Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* 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
}
}
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
You can’t perform that action at this time.