lazy function definitions in scala

后端 未结 6 1531
滥情空心
滥情空心 2021-02-02 16:49

I\'ve been learning scala and I gotta say that it\'s a really cool language. I especially like its pattern matching capabilities and function literals but I come from a javascri

6条回答
  •  旧时难觅i
    2021-02-02 17:18

    You can define a lazy val which is a function :

    lazy val foo = {
      val d = new Date
      () => { d }
    }
    
    println(foo())
    

    foo() will now return the same Date object each time, object which will be initialized the first time foo is called.

    To explain the code a little, the first time foo() is called { val d = new Date; () => { d } } is executed, d is assigned to a new date value then it evaluate the last expression () => { d } and assign it to the foo value. Then foo is a function with no parameters which return d.

提交回复
热议问题