返回顶部

收藏

Scala Lazy Evaluation

更多

lazyEvaluation.scala

// Contributed by John Williams
package examples

object lazyLib {

  /** Delay the evaluation of an expression until it is needed. */
  def delay[A](value: => A): Susp[A] = new SuspImpl[A](value)

  /** Get the value of a delayed expression. */
  implicit def force[A](s: Susp[A]): A = s()

  /** 
   * Data type of suspended computations. (The name froms from ML.) 
   */
  abstract class Susp[+A] extends Function0[A]

  /** 
   * Implementation of suspended computations, separated from the 
   * abstract class so that the type parameter can be invariant. 
   */
  class SuspImpl[A](lazyValue: => A) extends Susp[A] {
    private var maybeValue: Option[A] = None

    override def apply() = maybeValue match {
      case None =>
        val value = lazyValue
        maybeValue = Some(value)
        value
      case Some(value) =>
        value
    }

    override def toString() = maybeValue match {
      case None => "Susp(?)"
      case Some(value) => "Susp(" + value + ")"
    }
  }
}

object lazyEvaluation {
  import lazyLib._

  def main(args: Array[String]) = {
    val s: Susp[Int] = delay { println("evaluating..."); 3 }

    println("s     = " + s)       // show that s is unevaluated
    println("s()   = " + s())     // evaluate s
    println("s     = " + s)       // show that the value is saved
    println("2 + s = " + (2 + s)) // implicit call to force()

    val sl = delay { Some(3) }
    val sl1: Susp[Some[Int]] = sl
    val sl2: Susp[Option[Int]] = sl1   // the type is covariant

    println("sl2   = " + sl2)
    println("sl2() = " + sl2())
    println("sl2   = " + sl2)
  }
}

标签:scala

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. Harries 发表 2018-10-16 12:22:30 从Scala(2.10)类型的标签或符号获取Java类的任何方法?
  2. 博主 发表 2016-12-31 04:38:37 hadoop流水账之HBase,Spark和在Spark上操作HBase
  3. 博主 发表 2016-12-31 04:38:37 Java/Scala杂记之一
  4. 博主 发表 2016-12-31 04:38:37 Java/Scala杂记之二
  5. 博主 发表 2016-12-31 04:38:37 Java/Scala杂记之三
  6. 博主 发表 2016-12-31 04:38:37 Java/Scala杂记之三
  7. 博主 发表 2017-01-07 07:34:01 一年一语言之2016
  8. xiaoli.wang 发表 2018-09-10 13:30:56 穷人创业指南,告诉你没钱该如何创业?
  9. 炒饭 发表 2015-06-13 08:32:43 Scala学习(一)——类、对象和变量
  10. 炒饭 发表 2015-06-16 15:48:52 Scala学习(二)——成员,方法和构造方法
  11. 炒饭 发表 2015-06-18 07:42:29 Scala学习(三)——代码块和流程控制
  12. 炒饭 发表 2015-06-18 14:44:34 Scala学习(四)——类型