Home » Scala language

def keyword with example in Scala

def keyword used to initialize functions in Scala. In this tutorial, we will learn usage, syntax, and examples of Scala def keyword.
Submitted by Shivang Yadav, on June 22, 2019

Scala def keyword

The def keyword in Scala 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.

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;


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

Syntax explanation:

Here, Scala 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.

Example code:

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));


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.


Top MCQs

Comments and Discussions!

© https://www.includehelp.com some rights reserved.