Scala Methods and Functions
Scala has both methods and functions, with little semantic difference between the two. A Scala method is part of a class, while a function is an object that can be assigned to a variable. In other words, a function defined inside a class is a method.
Methods in Scala are similar to those in Java; a method is part of a class.
A function in Scala is a complete object; in fact, a Scala function is an object of a class that inherits from a Trait.
In Scala, use the val statement to define a function, and thedef statement to define a method.
class Test{
def m(x: Int) = x + 3
val f = (x: Int) => x + 3
}
Note:In some translations there is no distinction between function and method.
Method Declaration
The syntax for declaring a Scala method is as follows:
def functionName ([参数列表]) : [return type]
If you do not write the equals sign and the method body, the method is implicitly declared asabstract, so the type containing it is also an abstract type.
Method Definition
A method definition starts with a def keyword, followed by an optional parameter list, a colon : and the method's return type, an equals sign =, and finally the method body.
The syntax for defining a Scala method is as follows:
def functionName ([参数列表]) : [return type] = {
function body
return [expr]
}
In the above code, return type can be any valid Scala data type. Parameters in the parameter list can be separated by commas.
The following method adds two passed-in parameters and returns their sum:
Example
object
add
{
def
addInt
(
a
:
Int, b
:
Int
)
:
Int
=
{
var
sum
:
Int
=
0
sum
=
a + b
return
sum
}
}
If a method has no return value, it can return Unit, which is similar to Java's void, as shown in the example below:
Example
object
Hello
{
def
printMe
(
)
:
Unit
=
{
println
(
"Hello, Scala!"
)
}
}
Method Call
Scala provides several different ways to call methods:
The following is the standard format for calling a method:
functionName( 参数列表 )
If a method is called through an instance object, we can use a Java-like format (using the . symbol):
[instance.]functionName( 参数列表 )
The above example demonstrates defining and calling a method:
Example
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
}
}
The output of the code above is:
$ scalac Test.scala
$ scala Test
Returned Value : 12
Scala is also a functional language, so functions are at the core of the Scala language. The following function concepts help us better understand Scala programming: