Scala Function / Method Declaration

Now we know how to declare variables in Scala, Some of you now probably want try writing some methods. By default all variables passed in a method are mutable in Scala. Here are some rules for writing methods.

Rules for Scala Function / Method declaration
  • Return type declaration and semicolon are optional
  • Keyword return is optional
  • Every method parameter must be followed by type annotation
  • Curly braces are optional if the method just have the single line (Same as if else clause of Java)
  • Method names can contain characters like ‘.’ OR ‘*’ OR ‘+’ as Scala doesn’t have any native operators (all operators of Scala are methods)
  • Method with no parameters can be called without parentheses
  • Method with one parameter can be called without parentheses and . operator

Let’s take an example of various methods,

//Full Method Definition
def min(a: Int, b: Int): Int = { 
    return if (a > b) a else b;

//Return type, semicolon and return keyword are optional
def min(a: Int, b: Int) = { if (a > b) a else b }

//Curly braces are also optional for one liner methods
def min(a: Int, b: Int) = if (a > b) a else b 
//Curly braces required if method has more than one lines
def min(a: Int, b: Int) = {
    //Additional lines
    if (a > b) a else b 

//Methods with special characters
//Int class and other such classes has + method for adding numbers
5.+(20) //Returns 25

//Above single parameter method can also be called by another way
5 + 20  //Also returns 25

//Method with no parameters 
def printName() = println("BackToBazics!")
printName() //Method can be called with parentheses 
printName   //Method can also be called without parentheses

In my next post we’ll talk about Scala Classes, Objects & Singleton Objects.

nJoy Learning…..!!!!! 🙂

One thought on “Scala Function / Method Declaration”

Leave a Reply

Your email address will not be published. Required fields are marked *