In this post , let us learn about the expressions and functions in scala
Expressions
Expressions are the one which gets evaluated in scala . We have different operators to achieve this .Will look at those below .
Mathematical operators:
+ -> Addition
– -> Subtraction
* -> Multiplication
/ -> Division
& -> bitwise AND
| -> bitwise OR
^ -> bitwise exclusive OR
<< -> bitwise left shift
>> -> bitwise right shift
>>> -> right shift with zero extension only in scala
Relational operators:
== -> Equal to
!= -> not equal to
> -> greater than
>= -> greater than or equal to
< -> lesser than
<= -> lesser than or equal to
Boolean operators :
! -> negation(unary operator)
&& -> logical AND(binary operator)
|| -> logical OR(binary operator)
other operators:
+= , -= , *= , /=
Functions
Following is the function used for adding two values .
def – keyword
a and b – parameters
Int – data type (First letter must in capital)
1. Normal function :
def func (a: Int, b: Int ): Int =
{
a + b
}
println(func(20,10))
30
Its not mandatory to provide return type in the case of normal function . Below is the way I tried without any return type .
def func (a: Int, b: Int ) =
{
a + b
}
println(func(20,10))
30
2. Function without parameter
Function can also be without any parameter as like below .
// invoking with parenthesis
def func1 () : Int =42
println(func1())
42
Other way to invoke parameterless function in scala is the below option.
// invoking without parenthesis
def func1 () : Int =42
println(func1)
42
3.Recursive function
A function gets called continuously by itself .
def func1(a: String ,b: Int) : String = {
if (b==1) a
else a + (func1("Success",b-1))
}
println(func1("Success", 5))
SuccessSuccessSuccessSuccessSuccess
We must specify the return type for this .
def func1(a: String ,b: Int) = {
if (b==1) a
else a + (func1("Success",b-1))
}
println(func1("Success", 5))
identifier expected but '=' found.
def func1(a: String ,b: Int) : = {