Scala Methods and Functions

Scala has methods and functions, and the semantic difference between them is very small. Scala methods are part of a class, while functions are objects that can be assigned to a variable. In other words, a function defined within a class is a method.

Methods in Scala are similar to Java's; methods are part of a class.

Functions in Scala are complete objects; in fact, functions in Scala are objects of a class that inherits from a Trait.

In Scala, usevalstatement to define a function,defstatement to define a method.

class Test{
  def m(x: Int) = x + 3
  val f = (x: Int) => x + 3
}

Note:In some translations, function and method have no distinction.


Method Declaration

The format of a Scala method declaration is as follows:

def functionName ([参数列表]) : [return type]

If you don't write the equals sign and the method body, then the method is implicitly declared asabstract, and the type containing it is therefore also an abstract type.


Method Definition

A method definition starts with adefkeyword, followed by an optional parameter list, a colon:and the method's return type, an equals sign=, and finally the method body.

The format of a Scala method definition is as follows:

def functionName ([参数列表]) : [return type] = {
   function body
   return [expr]
}

In the above code,return typecan be any legal Scala data type. Parameters in the parameter list can be separated by commas.

The following method adds the two passed parameters and returns the 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 returnUnit, which is similar to Java'svoid, as in the following example:

Example

object Hello{
   def printMe( ) : Unit = {
      println("Hello, Scala!")
   }
}

Method Invocation

Scala provides several different ways to invoke methods:

The following is the standard format for invoking a method:

functionName( 参数列表 )

If a method is invoked using an instance object, we can use a Java-like format (using the.dot):

[instance.]functionName( 参数列表 )

The above example demonstrates defining and invoking 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
   }
}

After executing the above code, the output is:

$ scalac Test.scala 
$ scala Test
Returned Value : 12

Scala is also a functional language, so functions are the core of the Scala language. The following function concepts help us better understand Scala programming:

Function concept analysis and cases
Function Call-by-Name Specifying function parameter names
Functions - Variable Arguments Recursive Functions
Default Parameter Values Higher-Order Functions
Nested Functions Anonymous Functions
Partially Applied Functions Function Currying
Other Extensions