[Scala Basic series 02] Scala functions

Source: Internet
Author: User

The main contents of this article are as follows:

    • Variables and invariants
    • Functions and procedures
    • Parameters of the function
    • Semicolon
1. Variables and invariants 1.1. Variables

Scala's variables are divided into two types, Var and val. var, or variable, is similar to the variables we touch in other languages such as Java, and Val, is value, similar to the non-assignable constants we use in other languages, or the final variable.
Why this difference, this is because in many cases, you do not need a variable var, especially in functional programming, more obvious. The constant performance brings a lot of convenience to the program, so Scala emphasizes the concept of immutable (immutable). For an immutable discussion, subsequent articles will be discussed.

Define variable (var) and value (val)

Define a constant or variable, as follows:

Val name = "Chunni"= 5

Above, we do not specify the type of the variable, but the Scala compiler infers the data type through type inference (inference). Of course, the specified variable type can also be displayed, but unlike Java, the type is separated by a colon (:) after the variable name, for example:

Val Age:int = 30

In general, when the type is not easy to judge (for the reader, not the machine, the compiler can always infer the type), or may cause misunderstandings, it is best to display the designation to increase the readability of the program. Usually, omitting a type makes the program more concise and understandable when the type is obvious.
variables, even immutable values, can be the result of an expression:

Val msg = "Hello" + Name

Scala allows you to define more than one variable at a time.

var i, j = 5= "Anonym"

2. Functions and Procedures 2.1. Functions (function)

Now we can look at how to define the function.

def add (X:int, y:int): Int = {  + y}println ("2 + 3 =" + Add (2,3))

As you can see from the code above, the function definition starts with DEF, then the function name, followed by the argument list of the function in parentheses, separated by commas. Unlike Java or C, the type of the parameter appears after the parameter name, separated from the parameter name Colon. The type of the function (that is, the type of the return value) is separated by a colon after the argument list. After the function type, it is the equal sign "=" and then the body of the function surrounded by curly braces.
The function return type can be omitted because the compiler can infer it. However, for the readability of the code, the return type should be noted as much as possible, and it can be omitted only if the code is very short and can see the return type at a glance.

It should be stated that:

parameter types are not omitted because the compiler is not likely to infer the type of the parameter

The "=" between the function signature and the function body cannot be omitted when the function has a return value (that is, a function rather than a procedure)

2.1. Process (Procedure)

The purpose of the process is to have some kind of "side effect", rather than to get the results calculated. As mentioned above, a procedure is just a special function, specifically a function that has no return value, or that returns a unit of type.

def sayhito (name:string) {  println ("Hi," + name)}sayhito ("Nini")

From the above, the process does not need to indicate the return type, nor does it require "=". Some programmers keep the code style consistent with the function, and with "=", the compiler can accept it.

3. Parameters of the function

Scala supports named and optional parameters, and it also supports repeating parameters.

3.1. Named parameters

Named parameters allow you to specify parameter names when you pass a parameter, so that the position of the parameter is no longer important.

 def addUser (name:string, Age:int, phone:string) = {println (" User added, Nam E:%s, age:%d, phone number:%s '  //  Error:parameter ' age ' was already specified at parameter position 2  

In the above code, addUser(name = "Tim", phone = "702-201-2345", age = 33) named parameters are used so that the order of the parameters can be different from the function definition. In addition, named parameters can be mixed with normal positional parameters, for example addUser("Abby", phone = "702-201-3456", age = 28) .

It should be stated that:

In mixed use, however, the position of the normal parameter must match the function definition and therefore addUser("Abby", "702-201-3456", age = 28) compile an error, because ' phone ' should appear in the third item.

3.2. Default parameters

Similar to C + +, Scala supports default parameters that, when defined by a function, can specify default values for certain parameters so that some parameters can be omitted when called.

def log (msg:string, severity:string = "Info", Time:long = System.currenttimemillis ()) {  println ("[%d] < %s>%s "= System.currenttimemillis () + $log (" Use default parameters ") log (" specify Severity "," Warn ") log (" Specify Time ", time = t) log (" Specify both severity and time "," Warn ", T)

In the case of default parameters, if the default value meets the need, it can be called without passing in, for example log("use default parameters") , the function will use the default value directly. Of course you can display incoming parameters.

When only some of the parameters need to be passed in, their positions are clearly consistent with the definition, for example log("specify time", time = t) . At this point, the naming of parameters has played a big role. This is why named parameters and default parameters often appear together.

3.3. Repeating parameters

The following ' log ' function has a parameter that has a ' * ' after the type, which means that the parameter can be repeated for an indefinite number of times, including 0.

def log (msgs:string*) = {  println (msgs.getClass.getName)  println (msgs.mkstring (","))}log () Log ("One", "one", "one", "three" = Array ("One", "one", "three")//log (array)//  above line wouldn ' t compile, type mismatch, expected Stringlog (array: _*)

If you look at the results, you may have noticed that when the number of arguments is not 0 o'clock, msgs is actually an array inside. It is similar to array when used, except that a direct array cannot be passed in when called. This is because the repetition of the parameter is treated as an individual, rather than as a holistic view of all parameters.

If you need to pass the entire array (or another type of sequence), there is a workaround, that is, add a ' _* ' symbol, which is separated from the parameter by a comma, for example log(array: _*) .

4. Semicolon 4.1. In-line statements

Most of the time, our programming habits are a single line of statements, and most languages require a semicolon at the end of the statement, which is a waste for Scala designers, and Scala wants to save the programmer's keystrokes as much as possible, so Scala is designed to end the statement by default as the line ends. However, if you want to enter multiple statements within a line, the semicolon is unavoidable.

Val hi = "Hi, Nini"; println (msg)
4.2. Statement cross-line

If you need to enter statements that span rows, this often happens when you initialize a string or write a complex mathematical expression. Like what:

Val msg = "Hello everybody,"            + "My name is Nini"  //Error:value unary_+ are not a member of STRINGval ret = 3 + 4                          + 5

The code above does not treat the statement as you would expect, instead, it will be treated as a four line stand-alone statement, "Hello everybody," is assigned to MSG, the second line is wrong, the value of RET is 7, and the fourth line is a separate value of +5. If you need them to be treated as a cross-line statement, you have to use parentheses, or put the operator at the end of an unfinished line, and it will be treated as a sign of the end of the statement bit. Such as:

Val hi = "Hi, Nini"= ("Hello everybody,"           + "My name is Nini")    //A statement are not over if T He parentheses don ' t match= 3 + 4 +                //This was a sign that thestatementare not over 
   5println (ret)

This time, the MSG is correctly assigned, and RET is correctly calculated as 12.

Semicolon Inference Rule

The rules that are inferred by semicolons are simple.

    1. By default, the end of a line is treated as a semicolon, which is the end of the statement
    2. The following statements will be treated as not closed &nbsp;&nbsp; line ends in parentheses (parentheses () or brackets [] are available) &nbsp;&nbsp; line ends at a character that cannot end as a statement, such as infix operator (+,-,*,/, etc.)

[Scala Basic series 02] Scala functions

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.