Category : Scala | Sub Category : Scala Interview Questions | By Prasad Bonam Last updated: 2023-09-27 04:59:35 Viewed : 270
In Scala, you can define functions using the def
keyword. Here is the basic syntax for defining a function:
scaladef functionName(parameter1: Type1, parameter2: Type2, ...): ReturnType = { // Function body // ... // Optionally, return a value of ReturnType }
Let is break down each part of the function definition:
def
: This keyword is used to declare a function.
functionName
: Replace this with the name you want to give to your function. Choose a descriptive and meaningful name that reflects the functions purpose.
parameter1
, parameter2
, ...: These are the input parameters or arguments that the function takes. Each parameter is followed by a colon :
and its data type (Type1
, Type2
, etc.).
ReturnType
: Specify the data type of the value that the function returns. If the function doesnt return a value, you can use Unit
(similar to void
in other languages).
=
: The equals sign separates the function signature from its body.
{}
: Curly braces enclose the function body, where you write the code that defines what the function does.
Optionally, you can include a return
statement to explicitly specify the return value, but in Scala, it is common to omit it, and the last expression evaluated in the function body is automatically treated as the return value.
Here is an example of a simple Scala function that adds two integers and returns the result:
scaladef add(a: Int, b: Int): Int = { a + b }
In this example, add
is the function name, a
and b
are the parameters of type Int
, and the function returns an Int
. The function body simply calculates the sum of a
and b
, and that result is implicitly returned.
You can then call this function elsewhere in your code like this:
scalaval sum = add(5, 3) // Calls the add function and assigns the result (8) to the sum variable.
This is a basic example, and Scala allows you to define functions with a wide range of parameter types, including custom classes, and return various types of values, making it a versatile language for defining and using functions.