首页 > 解决方案 > What happens when return a lazy val from a function in Scala?

问题描述

I found the following code and I'm not sure how it works. This is Scala code with Play framework.

    ## route file ##

    GET /:object      @controllers.ResultsController.resultController(object)
    ## ResultsController file ##

    def resultController(object: SomeObject) = {
        getResult(object)
    } 

    def private getResult(object: SomeObject): Result = {
        lazy val result = computeResult(object) match {
            case Some(response) => JsonOk(response)
            case None => JsonInternalError(...)
        }
        result
    }

I'm not sure when result is evaluated. I mean, the return is something that must be evaluated when used, or is it resolved at the time of return?

The lazy characteristic leaves the context of the function?

在这种情况下,从不使用该值,仅作为 GET 请求的结果返回。

非常感谢!!!

标签: scalaplayframework

解决方案


是的,惰性result在内部被评估getResult以返回。Result- 你的返回类型getResult不是惰性的,实际上你不能将函数返回类型定义为惰性。如果由于某种原因你真的需要计算是惰性的,它可能应该是类似() => Resultor Future[Result]

此外,“在这种情况下,从不使用该值,仅作为 GET 请求的结果返回。 ”的想法显然是错误的。浏览器不理解 Scala,它理解 HTTP,这是一种文本格式。这意味着框架必须在引擎盖下的某个地方将您Result转换为文本形式(即序列化它),无论如何它肯定需要评估它。


推荐阅读