Scala Methods and Functions
Scala has both methods and functions, with a subtle difference in semantics. Scala methods are part of a class, while functions are objects that can be assigned to a variable. In other words, functions defined within a class are methods.
Methods in Scala are similar to those in Java, as they are part of the class composition.
Functions in Scala, on the other hand, are complete objects, essentially objects of classes that inherit from Traits.
In Scala, functions can be defined using the val statement, while methods are defined using the def statement.
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 declaration format for Scala methods is as follows:
def functionName ([parameter list]) : [return type]
If you omit the equals sign and the method body, the method is implicitly declared as abstract, and the type containing it is also an abstract type.
Method Definition
A method definition begins with the def keyword, followed by an optional parameter list, a colon :
, the method's return type, an equals sign =
, and finally, the method body.
The format for defining a Scala method is as follows:
def functionName ([parameter list]) : [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 the two input parameters and calculates the sum:
Example
object add{
def addInt( a:Int, b:Int ) : Int = {
var sum:Int = 0
sum = a + b
return sum
}
}
If a method does not return a value, it can return as Unit, which is similar to void in Java. An example is as follows:
Example
object Hello{
def printMe( ) : Unit = {
println("Hello, Scala!")
}
}
Method Invocation
Scala provides several different ways to invoke methods:
The standard format for calling a method is as follows:
functionName( [parameter list] )
If a method is called using an instance of an object, we can use a Java-like format (using the . operator):
[instance.]functionName( [parameter list] )
The above example demonstrates the definition and invocation of methods:
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
}
}
Executing the above code will output:
$ 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 functional concepts can help us better understand Scala programming: