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]
的对象作为构造函数参数。
hellotest1
使用非严格参数,并返回Test[Int]
的实例。创建a1
时,将获得elem = () => { println("hello"); 1 }
。因此,在通过应用elem创建a2
和a3
的情况下两次打印[[hello时,这是有意义的。test2
也使用非严格参数,并返回Test[Int]
的实例。创建b1
时,将获得elem = () => y
。 y
未评估,并绑定到呼叫者-test2
。当应用elem
创建b2
时,通过elem()
,y
被求值(因此打印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()//回声你好...
scalac -Vprint:_
查看捕获的元素的实现。