Learning is Evolving |Flat 25% off on all courses | Use coupon code LEARN25 During checkout |

 Enroll Now


31 / 52

Scala - Function Examples

Functions are program components which optionally take some input and perform some actions and optionally give some output. They are similar to methods of a class but functions exist without any classes too.

def functionName ([list of parameters]) : [return type] = {
   function body
   return [expr]


object Hello {
   def addNumbers( x:Int, y:Int ) : Int = {
      var sum:Int = 0
      sum = x + y
      return sum

In below example, calcSum is a function which takes 2 numbers as input and gives the sum of those 2 numbers as Integer output. This function is called inside the main Scala program.

There is another function dispDateTime to display the current date and time. It doesn't return any input, rather just performs the action of printing the date and time. The return type of non-returning functions is Unit, same as void in other languages, and is an optional keyword.

//this is import of non-default packages to access specific utilities
import java.text.SimpleDateFormat
import java.util.Calendar
//this is main class of the scala program
object HelloWorld {
  //this is the main method of the program
  //this is the method which called when the program is run

  def main(args: Array[String]) {
    println("Hello, world!") // prints Hello World

    //display current date time using a function

    var result: Int = 0;
    //get sum of 2 numbers using a function
    result = calcSum(5, 7);
    println("Result is:" + result)

  def dispDateTime(): Unit= {
    val now = Calendar.getInstance().getTime()
    //println is a function which take st
    println("Current time is " + "as below")

  def calcSum(a: Int, b: Int): Int = {
    var sum: Int = 0
    sum = a + b
    return sum