scalla
spark--scala --best performance--compatible
scala--codes--directly runs on jvm
--in python--extry layer created--python process which interacts with jvm
scala:
--------------
val -- like constant
var-- mutable--can change value
scala--infer--type(type inference)
val num = 5
by default it will take int.
Double--can take more precision
float--4 bytes(take less precision
val piSinglePrecision : Float = 3.1415f
(camelcase format)
for big range Long
val e:Long = 12131324242434243l
val smallNumber :Byte = 127
(127 to -127)
===========================================
s interpolation
val name = "Sasmit" //> name : String = Sasmit
println(s"Hello $name") //> Hello Sasmit
f interpolation
---------------------
val pi = 3.142 //> pi : Double = 3.142
println(f"the value of pi is $pi%.3f")
raw interpo
---------------
in raw form
println("hi \n how are you") //> hi
//| how are you
but with raw
println(raw"hi \n how are you") //> hi \n how are you
----------------------------------
string comaparision
-----------------------
== for string comparision
-------------------------
match case(switch in java)
val num = 1 //> num : Int = 1
num match {
case 1 => println("one")
case 2 => println("two")
case _ => println("something")
}
-----------------------
do while
---------------
at least code will be execute once.
while
---------------
expression block:
{ val x=10
x+20
70
}
return the last value
----------------------
==================================
supports:
object oriented style
functional programming style
---------------------------------------
transformInt(2,x=>x*x)
x=>x*x -- anonymous function(one time requirement)
Array:
-------------------
mutable
--searching based on index and first.
--adding a new element
--seraching is first
List
-----------------
b.head--1st element
b.tail--all except head
val c = List(1,3,4,6)
c.reverse
c.sum
for (i<-c) println(i)
internally holds the element in singly linked list
--searching not efficient
but adding a new element at the beginning--easy
10::c
adding new elemet at the beginning
Tupple:
---------------------
val x = ("Sasmit",20000,true)
holds element of differnt datatypes.
--row of record in db table
--can hold elements of different data types.
--it is very commnly used in spark
--and it is 1 based index
can access as x._1
if two elemts then works as key value pair
val y = (104,"Pawan")
val z = 104->"Pawan"
both are same
Range:
------------------------
val rng = 1 to 10
1 to 10
1 until 10 --means 1 to 9
--specify range of values
-------------------------
Set:
----------------
--holds only unique distinct values.
--cannot hold duplicates.
--order is not maintained
val zx = Set(1,1,1,2,2,3,4,5)
it will holds as Set(5,1,2,3,4)
--distinct values
--zx.min
zx.max
zx.sum
array is mutable
other immutable
Map:
----------------
collection of key value pair
val sd = Map(1 -> "Sasmit",2 -> "Garud")
sd.get(2)
keys are distinct
if u keep duplicates then first value will be discared.
------------------------------
2 modes of writings
repl--interactive manner
ide--bundle
functional programming --good fit when talk about library design and data crunching activities
pure functions:
--------------------------
input--solely determine the o/p
--function doesnt chnage its input vale
--no side effect
--only do whatever it is intended for
--all mathemetical function--pure
--dollar to rupee conversion--not pure.
------------
to check the purity of function:
--referential transparency
--
sqrt(4)--in all occurance-- replace with 2
--referentially transparent
First class function:
-----------------------------
we should be able to assign a function to a variable.
--treat function like values.
--in scala first class function
def dubler(i:Int):Int = { i*2}
val a = dubler(_)
a(2)
o/p--4
2, we should be able to pass a function as parameter to function.
def tripler(i:Int):Int = { i * 3}
def fun(i:Int,f:Int=>Int)={f(i)}
fun(5,tripler)
3, we shoud be able to retun a function from function
def func ={
x:Int => x*x
}
-----------------------------------
Higher order function:
----------------------------------
function--takes function as parameter or returns a function--
Map
--------
if n input--then n output rows.
works each row at a time
val a = 1 to 10
def doubler (i:Int):Int = { i*2}
a.map(doubler)
-------------------
Anonymous function
------------------
function with out any name.
a.map(x=> x*2)
in python it is called lambdas
-------------------------------------
Immutability
-----------------------
val and var
immutability is preferred
----------------------------------
Loop vs recursion vs tail recursion
---------------------------------------
loop
----------
def factorial(input:Int) :Int ={
vvar result :Int = 1
for(i <- 1 to input)
{
result = result * i
}
result
}
recursion
-------------
def factorial(input:Int):Int ={
if (input == 1) 1
else input * factorial(input-1)
}
needs memory space to hold this
5* factorial(4)
5*4*factorial(3)
5*4*3*factorial(2)
not good
tail recursion:
--------------------------
def factorial(input:Int,result:Int) = {
if(input ==1) result
else factorial(input-1,result*input)
}
factorial(4,1)
factorial(3,4)
factorial(2,12)
factorial(1,24)
in memory it will hold only factorial(1,24)
recursive call should be last statement in function
--highly efficient.
-------------------------------
Statement vs expresion
-------------------------
each line of code block-- statement
line of code that returns soem things--expression.
in scala--all expression.
val a = println("hello world")
Unit()
like void in java
-------------------------
Closure
---------------------
u can associate a state with function--
that is called closure.
scala type system
----------------------
Any
Anyval AnyRef
Char
Byte
Short
Int
Long
Float
Double
Unit
Boolean--true or false
Char
AnyRef
List
Seq
Tuple
String
Null
Nothing
only for reference type Null is valid
Nothing--no return type
val b = if (a == 5) 1 else println("Hello")
b:AnyVal
val b = if (a ==5) 2 else List(1,2)
b:Any
Operators:
-----------------------
u don't hv operators
--only methods
a+b
same as a.+(b)
to see list of methods --
a.
if more than one statements then use {}
Placeholder Syntax
-------------------------------
val a = 1 to 10
a.map(x*2)
give error
a.map(_*2)
a.reduce(_+_)
reduce--take 2 input
_ -- placeholder syntax
-------------------------------
Partially Applied functions
----------------------------------
def sumFunc(x:Int,y:Int):Int = {x+y}
val increment = sumFunc(1,_:Int)
one value fixed and one placeholder
sumFunc(4,8)
o/p--12
increment(12)
o/p-13
--act of creating brand new functions by fixing one or more parameters in a function.
def genricSum(x:Int,y:Int,f:Int => Int) = {
f(x) + f(y)
}
genricSum(2,3,x=>x)
----------------------------------
Function Currying:
---------------------------
Dividing the parameters into different groups.
def genricSum(f:Int=>Int)(x:Int,y:Int): Int={
f(x)+f(y)
}
genricSum(x=>x*x)(3,4)
val sumOfSquare = genricSum(x=>x*x)_
---------------------------------
=====================================
Object oriented sessions:
------------------------------
class persion {
data
+
behaviour
}
class Person(val name:String,val age:Int) //constructor
val p =new Person("Sasmit",30) //> p : sc3.Person = sc3$Person@46fbb2c1
//above class both name and age are class parameters
//these are not the class fields.
println(p.name) //> Sasmit
fields we can access by p.name but parameter we can access
class Student {
N_eyes = 2 // as this is fixed--class level functionality.("Static")
--in case of java we used to have a static keyword.
to get class level functionality:
use object
object Person {
//class level functionality | same like "static" in java
val N_Eyes =2
def canFly :Boolean =false
}
class Person(val name:String, val age:Int) {
//instance-level functionality
def salaryDoubler(salary:Int) = salary * 2
}
//companions--as we can use class level as well as object level
val person = new Person("Sasmit",30)
person.age
its like static as java
in a file both class and object have same name--
object level--same copy of every one
and class level--diffet values for each instance.
we can access class level functionaity and instance level functionality--this is called companion design partten.
===================================
class parameters and promoting to fields by putting var or val before it
class level functionality using obejcts
there is nothing like static in scala
design pattern where in a single file we have'object and class with same name this
design pattern is called a s companion.
object is for class level functionality
class is for instance level functionality
in scala the singleton design pattern is achived using object
singleton design pattern --achived by using object.
only one object/instance will be there.
===========================================
inheritance
--------------------------
class name first character as capital(better naming convention)
class Animal{
def eat = println("Animals")
}
class Cat extends Animal {
def preferedMeal = println("milk")
}
val cat = new Cat
cat.eat
cat.preferedMeal
if parent class method is private than child cann't access it
Multiple inheritance is not possible.
child class cannot extends frim 2 parent class.
---------------------------
Access modifier in scala
--------------------------
private:
protected:
u can call inside child class but not out.
public(no modifier)
=========================
abstract class:
-----------------------------
haves unimplemented methods and undefineded values.
whole purpose to create abstract class --to implement later by inheriting it in child later.
u can't create instance of abstract class.
come mothods can be defined in abstract class also
traits:
-----------------------
like abstract class use keywords traits.
multiples traits may be inherited by class
traits are like behivour
u cann't have constructor parameter in traits.
both abstarct class and traits can have implemented as well as unimplemented methods
--java we have interfaces-- totally unimplemented.
--traits-- we have both implemented and unimplemented methods.
multiple inheritance possible with the help of traits.
==========================================
Case Classes:
------------------------
special class--less code.
class parameters are automatically are promoted to fields.
object sc12 {
case class Person(name:String,age:Int)
//class parameter are automatically promoted to fields
val person1 = new Person("sasmit",30)
println(person1.name)
//sensible toString
println(person1.toString)
println(person1)
//equals and hashCode method implemented already
val person2 = new Person("Sasmit",30)
println(person1==person2)
//in case class internal values with be compared
//not the refernce point.
//have companion objects already--we don't have to create
//for that u need to use apply method.
val person3 = Person.apply("sasmit",30)
val person4 = Person("sasmit",30)
//even new keyword is not there.
//case class have handy copy method
val person5 = person2.copy(age = 45)
//note copy method is not defined--its available.
println(person5.age)
//case classs are serializable--can transfer over network.
}
Comments
Post a Comment