Why not suggest return in Scala

Source: Internet
Author: User
Tags anonymous throwable
why not suggest return in Scala


Using return in Scala, the compile will prompt the latest statement is method is automatically returned, and use of th return keyword is redundant. The warning is that the result of the last statement is automatically returned, and no return statement is required.
Scala does not recommend using the return keyword, which is very uncomfortable when you are just touching functional programming. Having a return will make the code result clearer, isn't it? After reviewing, the reasons why the return keyword is not recommended are collated in the following points. 1. To write a function rather than an instruction

An important idea of functional programming is to try to make the code consist of stateless functions, rather than giving instructions to the computer. For example

f (x) = x + 1    //Type 1.1

is a function.
Scala automatically returns the result of the last expression

def f (x:int) = x + 1    //Type 1.2
def f (x:int): Int = return x + 1     //Type 1.3

From the above two representations of using and not using return, it is not used to look closer to the function, and return is more like an instruction. 2.return Impact Type inference

The type inference mechanism in Scala automatically takes the type of the last expression as the return type, for example, in Formula 1.2, where the function automatically recognizes the result as an int type. If you use the return statement, you break the type inference mechanism, and you need to explicitly indicate the return type, such as Formula 1.3. 3. Return meaning blur using return

Sometimes using return makes the return of the code more confusing, and this ambiguity arises primarily from what layer of function the return is returning to.

def add (N:int, m:int): int = return n + M     //Type 3.1
def sum1 (ns:int*): int = ns.foldleft (0) (add)    //Type 3.2

For example, the code above is not a problem at the moment, but if it is written in the following form

def sum2 (ns:int*): Int = Ns.foldleft (0) ((n,m) = return n+m)    //Type 3.3

The intuitive sensation 3.3 should be equivalent to the 3.1+3.2. But in fact sum1 = 6, while sum2 is 1.
The reason for this is that the return statement directly returns the function it appears in. The result will be returned directly by the break Foldleft loop.
Let's look at another example:

def foo:int = { 
    val sumr:list[int] = Int = _.foldleft (0) ((n, m) + return n + m)
    Sumr (List) + SUMR (List (4,5,6))
}

First, an anonymous function is defined, and when the anonymous function is called, the return statement appears in the Foo function. So foo () = 1 4.NonLocalReturnControl

The return in Scala's loop is actually implemented by throwing exceptions, which are found after compilation

return value

was compiled into a

throw new Nonlocalreturncontrol (key/*metadata*/, value)

And the source of Nonlocalreturncontrol is:

Class nonlocalreturncontrol[@specialized T] (Val key:anyref, Val value:t) extends Controlthrowable {
    final override D EF fillinstacktrace (): Throwable = This
}

You can see that the Nonlocalreturncontrol exception inherits the Throwable, and the fillinstacktrace does not fill the stack information in order to improve performance overrides. This way, if we write in code to protect the code from crash:

def fun (n:int): String = {
    try {for
        (i <-0 to N) {
            if (I < 5) {
            }else{
                return "GT"
            }
        }
   ""
    }catch{case
        t:throwable = return t.tostring
    }
}

The resulting string is scala.runtime.NonLocalReturnControl, not the result we expected. 5. What should be done

In the actual development we will often encounter the seemingly must use return, what should be done. First, since Scala has provided the return keyword, it is not forbidden to use, but it needs to be considered clearly whether it must be done. In Scala's view, all loops that need to break with return can be replaced by a recursive return, and the performance aspect of Scala is specifically optimized for recursion.

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.