Categories
scala

Anonymous function in scala

In this post let us learn about the anonymous function in scala.

Anonymous function in scala

Anonymous function is the function without any specific name. It is also called as Lambda function .

Lambda is the word derived from the word lambda calculus which is the  mathematical expression of functional programming.

Basic syntax

To have a little introduction about the functions in scala , go through the previous blog in scala.

The following is the basic syntax to define anonymous function with single parameter.

val a: Int => Int = (x : Int) => x * 2
println(a(3))
6

There are alternative ways for defining the same , the followings are those.

val b = (x : Int) => x * 2
println(b(3))
6

For further information on the syntax of anonymous function in scala

val c = (_:Int) * 2
println(c(3)
6

With multiple parameters

If you have multiple parameters , need to mention the arguments within parenthesis. The below will be the syntax for anonymous function with multiple parameters.

val d: (Int,Int) => Int = (x : Int, y: Int) => x * y
println(d(3,3))
9

With no parameter

In the following example println(e) prints the instance , whereas println(e()) prints the value of the function . We might used to call objects in the former way but for lambda , we must use the latter way.

val e: () => Int = () => 2
println(e())
2

Using Curly braces

The following is the anonymous function defined using curly braces.

val f = { (colour: String) => colour.toInt}

MOAR syntactic sugar

val g: Int => Int = (x: Int) => x+1 — This line is equivalent to the below

val g: Int => Int = _+1
println(g(3))
4

val h: (Int,Int) => Int = (a,b) => a+b — This is equivalent to the below

val h: (Int,Int) => Int = _+ _
println(h(3,3))
6
Categories
scala

callbyvalue and callbyname in scala

In this post let us learn the topic callbyvalue and callbyname in scala.

Generating random number

Will see how to generate random number before starting the topic. This we are going to use in our further code segment .

  val r = scala.util.Random
  println(r.nextInt)
  println(r.nextInt)
  println(r.nextInt)
  println(r.nextInt)
1242716978
868935609
1888491218
-1140363327

callbyvalue

The value computes before invoking the function . And this use the same value whatever it evaluates everywhere the function invokes . In the below example , the value of a remains same while invoking it for two times .

syntax :

function_name(value_name : datatype)  

   val r = scala.util.Random
  callbyvalue(r.nextInt)
    def callbyvalue (a : Long) : Unit = {
      println(" value of a :" +a)
      println(" value of a :" +a)
    }
 value of a :1644239565
 value of a :1644239565

callbyname

Though we pass the expression , the expression evaluates newly at every time it invoked . In the below example , the value of a varies in each time we invoke .

syntax :

function_name(value_name : =>datatype) 

  val r = scala.util.Random
  callbyname(r.nextInt)
  def callbyname (a : => Long) : Unit = {
    println("value of a :" +a)
    println("value of a :" +a)
  }
value of a :761546004
value of a :-892955369

syntax difference

The syntax difference between callbyvalue and callbyname in scala is highlighted below .

function_name(value_name : datatype)  

function_name(value_name : =>datatype

https://beginnersbug.com/values-variables-and-datatypes-in-scala/

Categories
scala

Expressions and functions in scala

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) :  = {
Categories
scala

values variables and datatypes in scala

In this post , let us learn about values variables and datatypes in scala .

Values

Values are immutable which cannot be modified . In the below example , ValuesVariablesTypes is the object created for this tutorial .

  • val – keyword (only in lower case) .
  • Int – datatype  
object ValuesVariablesTypes extends App {
    val x : Int = 43 ;
    print(x)
}
43
Process finished with exit code 0

We are trying to modifying the value in the below case . It failed with reassignment error . Hence this immutable feature will not allow us to modify the values .

object ValuesVariablesTypes extends App {
    val x : Int = 43 ;
    print(x)
    x = 44 ;
}
reassignment to val
    x = 44 ;

It is not mandatory to specify the datatype as compiler can infer datatypes automatically . And so it worked for the below case also .

object ValuesVariablesTypes extends App {
    val x = 43 ;
    print(x)
}
43
Process finished with exit code 0

Datatypes

Few of the main datatypes along with ways to specifying as follows

Datatype specify with datatype specify without datatype
String val a : String = “Hello” val a = “Hello”
Boolean val b : Boolean = false val b = false
Char val c : Char = ‘ abc’ val c = ‘ abc’
Short(2bytes of length ) val d : Short =7416 val d = 7416
Long(4bytes of length ) val e : Long = 74167416 val e = 74167416
Long (for more than 4 bytes) val f : Long = 7416741674167416L val f = 7416741674167416L
Float val g : Float = 14.0f val g = 14.0f
Double val h : Double = 3.63 val h = 3.63

Variables

Variables can be modified which is the difference between values and variables .

object ValuesVariablesTypes extends App {
    var Y = 43 ;
    println(Y)
    Y = 44 ;
    print(Y)
}
43
44
Process finished with exit code 0

Hope this post gives an idea about values variables and datatypes in scala .

Categories
scala

How to get previous dates using scala

In this post, we will see how to get previous dates using scala.

Scala program – method 1

ZonedDateTime and ZoneId – to get the date and time based on the specific zone id which we prefers to 

DateTimeFormatter – to convert the date and time to a specific format

minusDays function helps us to get the previous dates using scala as below.

import java.time.{ZonedDateTime, ZoneId}
import java.time.format.DateTimeFormatter

object PreviousDate {
  def main(arr: Array[String]): Unit = {
    val previousday = ZonedDateTime.now(ZoneId.of("UTC")).minusDays(1)
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm'Z'")
    val result = formatter format previousday
    println(result)
  }
}
2021-10-01T05:21Z

Scala program – method 2

object YesterdayDate {
  def main(arr: Array[String]): Unit = {
    val today = java.time.LocalDate.now
    val yesterday_date= java.time.LocalDate.now.minusDays(1)
    println(today)
    println(yesterday_date)

  }
}
2021-10-02
2021-10-01

Scala program – method 3

import java.util._
import java.lang._
import java.io._
import java.time.Instant
import java.time.temporal.ChronoUnit


object YesterdayDate {
  def main(arr: Array[String]): Unit = {
    val now = Instant.now
    val yesterday = now.minus(1, ChronoUnit.DAYS)
    System.out.println(now)
    System.out.println(yesterday)
  }
}
2021-10-02T06:37:11.695Z
2021-10-01T06:37:11.695Z

https://github.com/ushanan/SparkFirstProject/blob/master/src/main/scala/com/firstscala/spark/YesterdayDate.scala