Scala Fun question-return statement

Source: Internet
Author: User

Value =?


def value:int = {def one (x:int): Int = {return x; 1} val = (x:int) = {return x; 2} 1 + one (2) + TW O (3)} println (value)

























Explain

It's complicated.


Explanation


Scala does not complain about unreachable code, therefore the code compiles fine. If you want to is warned about unreachable code and then use the compiler Option-ywarn-dead-code. If you want to see a compiler error instead of a warning, then in addition use the compiler option-xfatal-warnings.


The answer to this question can is found in sls§6.20:


A return expression Return E must occur inside the body of some enclosing named method or function. The innermost enclosing named method or function in a source program, F, must has an explicitly declared result type, and The type of E must conform to it. The return expression evaluates the expression E and returns its value as the result of F. The evaluation of any statements or expressions following the return expression is omitted.


For the first return x statement the enclosing named method was method one, but for the second return x statement the Enclo Sing named method is method value. When the function (3) was called as part of the expression 1 + one (2) + A (3), then the result 3 is returned as the Res Ult of method value.


BTW, returning from a nested anonymous function was implemented by throwing and catching a scala.runtime.NonLocalReturnCont Rol.


The most common reason your actually would want to return from inside a nested function was to break out of a imperative fo R-comprehension or resource control block. See the answers to the Stack Overflow question Purpose of ' return ' statement in Scala? For a further discussion of that aspect


The return statement for Scala can be consulted:

http://stackoverflow.com/questions/3770989/purpose-of-return-statement-in-scala/3771243#3771243

Scala Fun question-return statement

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.