Scala Basics Tutorial (V): functions, Closures _scala

Source: Internet
Author: User
Tags function definition

A function is a set of statements that perform a task together. You can put your code in a separate function. How to divide your code between different functions, but logically, partitioning is usually to allow each function to perform a specific task.

Scala has functions and methods, and our terminology says that the methods and functions are interchangeable in small differences. The Scala approach is to have a name, signature, optional annotation, and some bytecode, such as in Scala, where a function is part of a complete object class that can be assigned to a variable. In other words, a function, which is defined as a member of some object, is called a method.

function definitions can appear anywhere in the source file, Scala allows the definition of nested functions, which is the internal function definition of other function definitions. The most important point to note is that Scala's function names can resemble +, + +, ~, &,-,--,,/,: And so on. function declaration:

Scala's function declaration has the following form:

def functionname ([List of parameters]): [Return type]

The abstract enclosing type is the abstraction itself, if the method that closes the equals sign and the method body is implicitly declared. function definition:

The Scala function definition has the following form:

def functionname ([List of parameters]): [return type] = {
function body
return [expr]
}

Here, the return type can be any valid Scala data type, and the argument list will be with commas and arguments, and the return value type list separator variable is optional. Very similar to Java, a return statement can return a value when a function expression is available. Here is a function that adds two integers and returns:

Object add{
def addint (A:int, b:int): Int = {
var sum:int = 0
sum = a + b
return sum
}
}

function, which does not return anything, can return this equivalent to void in Java and indicates that the function does not return any cells. Scala does not return anything function is called a procedure. Here is the syntax

Object hello{
Def printme (): unit = {
println ("Hello, scala!")
}
}
Call Function:

Scala provides some syntax changes to invoke the method. Here's a standard way to invoke a method:

functionname (List of parameters)

If a function is invoked by an instance of an object, the following Java dot notation is used:

[Instance.] functionname (List of parameters)

Here is an example to define, and then call a function:

Object Test {
def main (args:array[string]) {
println ("Returned Value:" + addint (5,7));
}
def addint (A:int, b:int): Int = {
var sum:int = 0
sum = a + b
return sum
}
}

Let's compile and run the above program, which will produce the following results:

C:/>scalac Test.scala
C:/>scala Test
Returned VALUE:12
C:/>

Scala functions are at the heart of Scala programming, which is why Scala is assumed to be a functional programming language. Here are some important concepts that Scala programmers understand about the relevant Scala functions.

Functions are called by name

Using named parameter functions

function uses variable parameters

Recursive functions

Default parameter values

Higher order functions

Nested functions

anonymous functions

Partial application function

Gerty function

A closure is a function, and its return value depends on the value of declaring one or more variables outside of this function. Consider the following piece of code that uses an anonymous function:

Val multiplier = (i:int) => I * 10

Here, the unique variable used in the function body, I * 0, is the I, which is defined as a function of a parameter. Now, let's look at another piece of code:

Val multiplier = (i:int) => i *factor

There are two multipliers for free variables: I and factor. One of the i is a formal function parameter. Therefore, it is bound to a new value at each invocation of the multiplier. However, factor is not a formal argument, then what is this. Let's add one line of code:

var factor = 3

Val multiplier = (i:int) => i *factor

Now, Factor has a variable that has a reference variable outside the function, but is a closed range. Let's try the following example:

Object Test {

def main (args:array[string]) {

println ("Muliplier (1) value =" + multiplier (1))

println ("Muliplier (2) value =" + multiplier (2))

}

var factor = 3

Val multiplier = (i:int) => I * factor

}

Let's compile and run the above program, which will produce the following results:

C:/>scalac Test.scala

C:/>scala Test

Muliplier (1) value = 3

Muliplier (2) value = 6

C:/>

The function above refers to factor and reads the current value for each time. If the function does not have an external reference, it is enclosing itself. No external environment is required.

Consider the following simple example, we give the Val variable of a string type:

Object Test {
Val greeting:string = "Hello, world!"
def main (args:array[string]) {
println (greeting)
}
}

Here, the value type above is borrowed from Java java.lang.String, because Scala's string is also a Java string. This is very nice to note: Each Java class can be used in Scala. Therefore, Scala does not have a string class and uses the Java string string class directly. Therefore, this chapter has been written to keep the basis of Java string.

In Scala, as in Java, a string is an immutable object, that is, an object that cannot be modified. objects, on the other hand, can be modified, such as an array object, called a mutable object. Since strings are very useful objects, in the remainder of this section, we are now most important to understand the method definitions of class java.lang.String.

From:http://www.yiibai.com/scala/scala_basic_syntax.html

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.