×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala def Keyword

By IncludeHelp Last updated : October 07, 2024

The 'def' Keyword

The def keyword is used to declare functions and methods in Scala. Scala being ignorant on the data types does the same with the return type of a function. Declaring and defining a function in Scala does not strictly require a return type. The def keyword usage makes the Scala program more flexible.

The function or methods that are defined using Scala def keyword get evaluated when they are called. This practice reduces the load on compiler because if a function is not called in some case. It is not evaluated.

Anonymous function

A function is said to be an anonymous function ( without a name ) if it is declared without using the def keyword and cannot be referenced. So, the functions with def keyword are used when the function call is required. And giving a name to it is important and using def keyword allows it.

Syntax (Declaration)

def function_name(arguments ) : returntype;

Syntax Definition

def function_name(arguments) : returntype {
    //code to be executed...
}

Syntax Explanation

Here, def keyword is used to define the function, the set of arguments of the function are enclosed in the brackets and an optional return type can also be given.

Scala Example of def Keyword

object MyClass {
      def add(x:Int, y:Int) : Int = {
          var sum = x+y ; 
          return sum; 
      }

      def main(args: Array[String]) {
         print("sum of x + y = " + add(25,10));
      }
   }

Output

sum of x + y = 35

Code Explanation

The above code prints the sum of two numbers using a function. The function add is used to add two numbers and returns their result. The function used Int return type to return the sum of two numbers passes as arguments of the function. The returned value is printed using the print function in the main class.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.