Wednesday, December 3, 2014
Scala is also a functional language and provides the flexibility to the programmer to use classes and methods as in a object oriented language along with pure functions. Functions in Scala are also objects. This article provides a brief introduction to using functions in Scala.

def is keyword used to define functions in Scala. A Scala function definition is typically of the form,

def FunctionName ( arg1 : Type, arg2 : Type ) : ReturnType = {
  Expression
}

As a simple example let us consider a Scala function to add two numbers.

object Foo {
  def sum ( arg1 : Int, arg2 : Int ) : Int = {
    arg1 + arg2
  }
  
  def main ( args : Array[String] ) {
    println(sum(10,20))
  }
}

Some key aspects when working with Scala functions.
  • Function parameters always need an explicit type specification though type inference can be used for variables in Scala.
  • Return type need not be specified.
  • return keyword can be omitted if the last expression is what needs to be returned
  • Using return type as Unit is same as using void in Java.
  • def doSomething () : Unit = {
       println("I am a function")
    }
    
  • Leaving out equal sign (=) in function definition is a common mistake when working with Scala functions. When a function doesn't return anything it is ok to ignore the equal sign. It is a good practice to always put equals sign even when the function doesn't return anything.

Default Parameter Values

Scala supports specifying default values for function parameters like Java.

object Foo {
  def compute ( arg1 : Int, arg2 : Int, arg3 : Int = 1 ) = {
    ( arg1 + arg2 ) * arg3
  }
  
  def main ( args : Array[String] ) {
    println(compute(5,10))
    println(compute(5,10,2))
  }
}

Function with Variable Arguments

Scala supports functions with variable number of arguments for the last parameter.

object Foo {
  def doSomething ( input : Int* ) = {
    for ( arg <- input ) {
      println(arg)
    }
  }

  def main ( args : Array[String] ) {
    doSomething(10, 20, 30)
  }
}

Proceed to read more Scala Tutorials.

0 comments :

Post a Comment

Contact Form

Name

Email *

Message *

Back to Top