lazy function definitions in scala

后端 未结 6 1518
滥情空心
滥情空心 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条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-02 17:31

    I think what you mean "lazy function" is function literal or anonymous function.

    In Scala you could do things like this, very similar to the javascript code you posted.

    val foo = () => {
        val t = new Date()
        val foo = () => {t}
    
        foo()
    }
    
    println ("Hello World:" + foo())
    

    The main difference is that:

    • You could not re-assignment the outer foo
    • There is no "function" keyword, instead you use something like (s:String) => {code}
    • The last statement is the return value of a block, so you don't need add "return".

提交回复
热议问题