Scala function explained in detail

 212 total views,  2 views today

Welcome to Scala series. This tutorial is about the Scala function explained in detail.

Scala function is similar to a method but a function doesn’t have any name. It is also called an anonymous function as it not holding a name to it.

A function has a sequence of statements which wrapped in a block. Each function performs a certain task based on its statements.

A function is not defined using def keyword. A function is just an expression with input parameters and a set of statements.

A function can be assigned to a variable and a function can be passed as an argument to another function.

A simple function example

(i:Int,j:Int) => i+j

The above function accepts two arguments and returns the sum of two arguments.

Function Syntax

(arguments) => (Expression involving arguments)

What about the return type of the function?

Function’s last expression value will be considered as the return value and scala is intelligent enough to identify the type on its own.

Function can be assigned to a variable

var myfunc = (i: Int, j: Int) => i + j
println(myfunc(2, 4))

Output

6

Function without a parameter

 var myfunc = () => 10*2+1
 println(myfunc())

Output

21

Function passing function example

object StaticReference {

  def main(ar1: Array[String]): Unit = {
    var myfunc = () => 10 * 2 + 1
    println(add(myfunc, 2, 3, 4))
  }

  def add(func: () => Int, i: Int, j: Int, z: Int): Int = {
    func() + i + j + z
  }
}

Output

30

References: Official documentation

Thanks for reading and hope you like this tutorial. Please leave a comment and give us a thumbs up!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.