Scala中的惰性求值,重击和函数关闭

问题描述 投票:1回答:1
case class Test[A](elem: () => A)

object Fun extends App {

  def test1(v: => Int): Test[Int] = Test(() => v)

  val a1 = test1({ println("hello"); 1 })
  val a2 = a1.elem() //echoes hello
  val a3 = a1.elem() //echoes hello

  def test2(v: => Int): Test[Int] = {
    lazy val y = v
    Test(() => y)
  }

  val b1 = test2({ println("hello"); 1 })
  val b2 = b1.elem() //echoes hello
  val b3 = b1.elem() //doesn't echo hello. Is function closure at work here?
}

Test是一个案例类,它使用类型为Function0[A]的对象作为构造函数参数。

test1使用非严格参数,并返回Test[Int]的实例。创建a1时,将获得elem = () => { println("hello"); 1 }。因此,在通过应用elem创建a2a3的情况下两次打印[[hello时,这是有意义的。test2也使用非严格参数,并返回Test[Int]的实例。创建b1时,将获得elem = () => yy未评估,并绑定到呼叫者-test2。当应用elem创建b2时,通过elem()y被求值(因此打印

hello

)然后缓存结果为1。创建elem()时,随后调用b3会使用评估值。但是,由于y并不是elem的本地语言,所以所有这些操作唯一的方法就是通过闭包。准确吗?

注意:我已经看过这里发布的示例:Scala lazy evaluation and apply function,但这并不是我想要理解的]

案例类Test [A](elem:()=> A)对象Fun扩展了App {def test1(v:=> Int):Test [Int] = Test(()=> v)val a1 = test1( {println(“ hello”); 1})val a2 = a1.elem()//回声你好...

scala closures lazy-evaluation thunk
1个回答
1
投票
您可以使用scalac -Vprint:_查看捕获的元素的实现。
© www.soinside.com 2019 - 2024. All rights reserved.