lazy function definitions in scala

后端 未结 6 1517
滥情空心
滥情空心 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

    All that complicated code in JavaScript appears to just try to cache the value of the date. In Scala, you can achieve the same thing trivially:

    lazy val foo = new Date
    

    And, if don't even want to make a val, but want to call a function that will only execute the expensive code if it needs it, you can

    def maybeExpensive(doIt: Boolean, expensive: => String) {
      if (doIt) println(expensive)
    }
    maybeExpensive(false, (0 to 1000000).toString)  // (0 to 1000000).toString is never called!
    maybeExpensive(true, (0 to 10).toString)        // It is called and used this time
    

    where the pattern expensive: => String is called a by-name parameter, which you can think of as, "Give me something that will generate a string on request." Note that if you use it twice, it will regenerate it each time, which is where Randall Schultz' handy pattern comes in:

    def maybeExpensiveTwice(doIt: Boolean, expensive: => String) {
      lazy val e = expensive
      if (doIt) {
        println(e)
        println("Wow, that was " + e.length + " characters long!")
      }
    }
    

    Now you generate only if you need it (via the by-name parameter) and store it and re-use it if you need it again (via the lazy val).

    So do it this way, not the JavaScript way, even though you could make Scala look a lot like the JavaScript.

提交回复
热议问题