Scala supports functional programming approach. It provides rich set of built-in functions and allows you to create user defined functions also.

In scala, functions are first class values. You can store function value, pass function as an argument and return function as a value from other function. You can create function by using def keyword. You must mention return type of parameters while defining function and return type of a function is optional. If you don’t specify return type of a function, default return type is Unit.


You can create function with or without = (equal) operator. If you use it, function will return value. If you don’t use it, your function will not return anything and will work like subroutine.

Scala functions don’t use return statement. Return type infers by compiler from the last expression or statement present in the function.

Scala Function Example without using = Operator

The function defined below is also known as non parameterized function.

This is a simple function

Scala Function Example with = Operator


Scala Parameterized Function Example

when using parameterized function you must mention type of parameters explicitly otherwise compiler throws an error and your code fails to compile.


Function Parameter with Default Value

Scala provides a feature to assign default values to function parameters. It helps in the scenario when you don’t pass value during function calling. It uses default values of parameters.

Let’s see an example.

15 12 0

Scala Function Named Parameter Example

In scala function, you can specify the names of parameters during calling the function. In the given example, you can notice that parameter names are passing during calling. You can pass named parameters in any order and can also pass values only.

Let’s see an example.

15 15 15

That’s all for Functions in Scala. Happy Learning!!

Leave a Reply

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