Friday, 7 April 2017

SCALA BASICS Practice on 01 Apr 2017

`Scala` means `Scalable Language`

`Scala`is Functional + Object Oriented Programming Language

In Java:
------------
1. Primitive data types (int, float, double, long ...)
2. Wrapper Classes (integer, Float, Double, Long ..)

Wrapper Classes are possible to do `Serialization and DeSerialization`

Java Syntax:
-----------------
<data type> <variable name> = <data> ;



In Scala:
-------------------
Everything is `Object`


Scala Syntax:
-----------------
val <variable name> : <data type> = <data>

var <variable name> : <data type> = <data>


val => value => it is immutable (we can't change the reference)

var => variable => it is mutable (we can change the reference)


orienit@kalyan:~$ scala
Welcome to Scala 2.11.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_66-internal).
Type in expressions for evaluation. Or try :help.

scala> 

`Scala` Provides `REPL` functionality.

`REPL` means Read Evaluate Print Loop

`REPL` functionality already there in `Python` and `R` programming languages

---------------------------------------------------
scala> val name : String = "kalyan"
name: String = kalyan

scala> name = "xyz"
<console>:12: error: reassignment to val
       name = "xyz"
            ^

scala> var name : String = "kalyan"
name: String = kalyan

scala> name = "xyz"
name: String = xyz

---------------------------------------------------
`Scala` provides `Type Infer`
---------------------------------------------------
Based on the `data` it will find the `data type`


scala> val name : String = "kalyan"
name: String = kalyan

scala> val name = "kalyan"
name: String = kalyan

scala> val id = 1
id: Int = 1

scala> val id = 1.5
id: Double = 1.5

scala> val id = 1l
id: Long = 1

scala> val id = 1f
id: Float = 1.0


---------------------------------------------------
scala> val id = 1
id: Int = 1

scala> val id = 1l
id: Long = 1

scala> val id = 1f
id: Float = 1.0

scala> val id = 1d
id: Double = 1.0

scala> val id : Long = 1
id: Long = 1

scala> val id : Float = 1
id: Float = 1.0

scala> val id : Double = 1
id: Double = 1.0

---------------------------------------------------

scala> a.toInt
res4: Int = 1

scala> a.toDouble
res5: Double = 1.0

scala> a.toFloat
res6: Float = 1.0

scala> a.toLong
res7: Long = 1

scala> a.toChar
res8: Char = ?


---------------------------------------------------
`Scala` Provides `Operator Overloading` simillar to `C++`
---------------------------------------------------
scala> val a = 1
a: Int = 1

scala> val b = 2
b: Int = 2

scala> val c = a + b
c: Int = 3

scala> val c = a.+(b)
c: Int = 3

scala> val c = a.-(b)
c: Int = -1

scala> val c = a.*(b)
c: Int = 2

---------------------------------------------------

a + b   <===>  a.+(b)

a - b   <===>  a.-(b)

a * b   <===>  a.*(b)

---------------------------------------------------

scala> a < b
res0: Boolean = true

scala> a <= b
res1: Boolean = true

scala> a >= b
res2: Boolean = false

scala> a > b
res3: Boolean = false

---------------------------------------------------

scala> a.
!=   >>            isInfinite      min              toInt           
%    >>>           isInfinity      round            toLong          
&    ^             isNaN           self             toOctalString   
*    abs           isNegInfinity   shortValue       toRadians       
+    byteValue     isPosInfinity   signum           toShort         
-    ceil          isValidByte     to               unary_+         
/    compare       isValidChar     toBinaryString   unary_-         
<    compareTo     isValidInt      toByte           unary_~         
<<   doubleValue   isValidLong     toChar           underlying      
<=   floatValue    isValidShort    toDegrees        until           
==   floor         isWhole         toDouble         |               
>    getClass      longValue       toFloat                          
>=   intValue      max             toHexString                      


---------------------------------------------------
if, if else, if else if expressions in Scala
---------------------------------------------------

if(exp1) { body1 }

if(exp1) { 
body1 
}

---------------------------------------------------

if(exp1) { body1 } else { body2 }

if(exp1) { 
body1 
} else { 
body2 
}


Wrong in `Scala Prompt`
---------------------------------------------------
if(exp1) { 
body1 

else { 
body2 
}

if(exp1) { 
body1 
} else 

body2 
}

---------------------------------------------------
if(exp1) { body1 } else if(exp2) { body2 }

if(exp1) { 
body1 
} else if(exp2) { 
body2 
}


if(exp1) { 
body1 
} else if(exp2) { 
body2 
} else if(exp3) { 
body3 
}

---------------------------------------------------
val a = 10
val b = 20
val c = 30

---------------------------------------------------

scala> val a = 10
a: Int = 10

scala> val b = 20
b: Int = 20

scala> val c = 30
c: Int = 30


scala> if(a > b) println("nothing")

scala> if(a < b) println("i am there")
i am there

scala> if(a < b) println("i am there") else println("nothing")
i am there

scala> if(a > b) println("i am there") else println("nothing")
nothing

scala> if(a > b) println("i am there") else if(a < b) println("nothing") 
nothing

---------------------------------------------------
Arrays in Java:
---------------------------------------------------
<data type>[] <variable name> = {};

<data type>[] <variable name> = new <data type>[size];

String[] names = {"anil", "raj", "venkat"}

or

String[] names =  new String[3];
names[0] = "anil";
names[1] = "raj";
names[2] = "venkat";

---------------------------------------------------
Arrays in Scala:
---------------------------------------------------
val <variable name> : Array[<data type] = Array[<data type](...)

val <variable name> : Array[<data type] = new Array[<data type](size)


val names : Array[String] = Array[String]("anil", "raj", "venkat")

or

val names : Array[String] = new Array[String](3)
names(0) = "anil"
names(1) = "raj"
names(2) = "venkat"


---------------------------------------------------

scala> val names : Array[String] = Array[String]("anil", "raj", "venkat")
names: Array[String] = Array(anil, raj, venkat)

scala> names(0)
res14: String = anil

scala> names(1)
res15: String = raj

scala> names(2)
res16: String = venkat

---------------------------------------------------

scala> val names : Array[String] = new Array[String](3)
names: Array[String] = Array(null, null, null)

scala> names(0) = "anil"

scala> names(1) = "raj"

scala> names(2) = "venkat"

scala> names
res20: Array[String] = Array(anil, raj, venkat)

scala> names(0)
res21: String = anil

scala> names(1)
res22: String = raj

scala> names(2)
res23: String = venkat

---------------------------------------------------

scala> val names = Array[String]("anil", "raj", "venkat")
names: Array[String] = Array(anil, raj, venkat)

scala> val names = Array("anil", "raj", "venkat")
names: Array[String] = Array(anil, raj, venkat)

---------------------------------------------------

val nums = Array(1,2,3,4,5,6,7,8,9,10)

---------------------------------------------------
scala> val nums = Array(1,2,3,4,5,6,7,8,9,10)
nums: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> for(x <- nums) println(x)
1
2
3
4
5
6
7
8
9
10

scala> for(x <- nums) if(x %2 == 0) println(x)
2
4
6
8
10

scala> for(x <- nums if(x %2 == 0) ) println(x)
2
4
6
8
10

scala> for(x <- nums) if(x %2 == 0) println("Even Number: " + x) else println("Odd Number: " + x)
Odd Number: 1
Even Number: 2
Odd Number: 3
Even Number: 4
Odd Number: 5
Even Number: 6
Odd Number: 7
Even Number: 8
Odd Number: 9
Even Number: 10


---------------------------------------------------
for(x <- nums) 
if(x %2 == 0) {
println("Even Number: " + x) 
} else {
println("Odd Number: " + x)
}
---------------------------------------------------

scala> for(x <- nums) 
     | if(x %2 == 0) {
     | println("Even Number: " + x) 
     | } else {
     | println("Odd Number: " + x)
     | }
Odd Number: 1
Even Number: 2
Odd Number: 3
Even Number: 4
Odd Number: 5
Even Number: 6
Odd Number: 7
Even Number: 8
Odd Number: 9
Even Number: 10

---------------------------------------------------
String Interpolation:
---------------------------------------------------
val name = "kalyan"
val course = "spark"
val percentage =  80.5
val count = 100
---------------------------------------------------

val exp1 = "name is " + name + ", course is " + course

val exp2 = "name is $name, course is $course"

val exp3 = s"name is $name, course is $course"

val exp4 = s"name is $name, percentage is $percentage"

val exp5 = s"name is $name, percentage is $percentage%.3f"

val exp6 = f"name is $name, percentage is $percentage%.3f"

val exp7 = s"name is $name\ncourse is $course"

val exp8 = raw"name is $name\ncourse is $course"

---------------------------------------------------
---------------------------------------------------
scala> val name = "kalyan"
name: String = kalyan

scala> val course = "spark"
course: String = spark

scala> val percentage =  80.5
percentage: Double = 80.5

scala> val count = 100
count: Int = 100

---------------------------------------------------

scala> val exp1 = "name is " + name + ", course is " + course
exp1: String = name is kalyan, course is spark

scala> val exp2 = "name is $name, course is $course"
exp2: String = name is $name, course is $course

scala> val exp3 = s"name is $name, course is $course"
exp3: String = name is kalyan, course is spark

scala> val exp4 = s"name is $name, percentage is $percentage"
exp4: String = name is kalyan, percentage is 80.5

scala> val exp5 = s"name is $name, percentage is $percentage%.3f"
exp5: String = name is kalyan, percentage is 80.5%.3f

scala> val exp6 = f"name is $name, percentage is $percentage%.3f"
exp6: String = name is kalyan, percentage is 80.500

scala> val exp7 = s"name is $name\ncourse is $course"
exp7: String =
name is kalyan
course is spark

scala> val exp8 = raw"name is $name\ncourse is $course"
exp8: String = name is kalyan\ncourse is spark


---------------------------------------------------
Collections in `Scala`
---------------------------------------------------
In scala we have 2 types of collections:

1. immutable collections (scala.collection.immutable)

2. mutable collections (scala.collection.mutable)

---------------------------------------------------

scala> import scala.collection.immutable.
::                    LongMap                SortedMap        
AbstractMap           LongMapEntryIterator   SortedSet        
BitSet                LongMapIterator        Stack            
DefaultMap            LongMapKeyIterator     Stream           
HashMap               LongMapUtils           StreamIterator   
HashSet               LongMapValueIterator   StreamView       
IndexedSeq            Map                    StreamViewLike   
IntMap                MapLike                StringLike       
IntMapEntryIterator   MapProxy               StringOps        
IntMapIterator        Nil                    Traversable      
IntMapKeyIterator     NumericRange           TreeMap          
IntMapUtils           Page                   TreeSet          
IntMapValueIterator   PagedSeq               TrieIterator     
Iterable              Queue                  Vector           
LinearSeq             Range                  VectorBuilder    
List                  RedBlackTree           VectorIterator   
ListMap               Seq                    VectorPointer    
ListSerializeEnd      Set                    WrappedString    
ListSet               SetProxy                                



---------------------------------------------------

scala> import scala.collection.mutable.
AVLIterator            LinkedListLike              
AVLTree                ListBuffer                  
AbstractBuffer         ListMap                     
AbstractIterable       LongMap                     
AbstractMap            Map                         
AbstractSeq            MapBuilder                  
AbstractSet            MapLike                     
AnyRefMap              MapProxy                    
ArrayBuffer            MultiMap                    
ArrayBuilder           MutableList                 
ArrayLike              ObservableBuffer            
ArrayOps               ObservableMap               
ArraySeq               ObservableSet               
ArrayStack             OpenHashMap                 
BitSet                 PriorityQueue               
Buffer                 PriorityQueueProxy          
BufferLike             Publisher                   
BufferProxy            Queue                       
Builder                QueueProxy                  
Cloneable              ResizableArray              
DefaultEntry           RevertibleHistory           
DefaultMapModel        Seq                         
DoubleLinkedList       SeqLike                     
DoubleLinkedListLike   Set                         
FlatHashTable          SetBuilder                  
GrowingBuilder         SetLike                     
HashEntry              SetProxy                    
HashMap                SortedSet                   
HashSet                Stack                       
HashTable              StackProxy                  
History                StringBuilder               
ImmutableMapAdaptor    Subscriber                  
ImmutableSetAdaptor    SynchronizedBuffer          
IndexedSeq             SynchronizedMap             
IndexedSeqLike         SynchronizedPriorityQueue   
IndexedSeqOptimized    SynchronizedQueue           
IndexedSeqView         SynchronizedSet             
Iterable               SynchronizedStack           
LazyBuilder            Traversable                 
Leaf                   TreeSet                     
LinearSeq              Undoable                    
LinkedEntry            UnrolledBuffer              
LinkedHashMap          WeakHashMap                 
LinkedHashSet          WrappedArray                
LinkedList             WrappedArrayBuilder      

---------------------------------------------------

---------------------------------------------------
val list = List(1,2,3,4,5)

val list = List[Int](1,2,3,4,5)

val seq = Seq[Int](1,2,3,4,5)

val set = Set[Int](1,2,3,4,5)

val vec = Vector[Int](1,2,3,4,5)

val str = Stream[Int](1,2,3,4,5)

---------------------------------------------------

val st = Stack[Int](1,2,3,4,5)

val qu = Queue[Int](1,2,3,4,5)

---------------------------------------------------
scala> val st = Stack[Int](1,2,3,4,5)
<console>:11: error: not found: value Stack
       val st = Stack[Int](1,2,3,4,5)
                ^
scala> val qu = Queue[Int](1,2,3,4,5)
<console>:11: error: not found: value Queue
       val qu = Queue[Int](1,2,3,4,5)
                ^

---------------------------------------------------
val st1 = scala.collection.immutable.Stack[Int](1,2,3,4,5)

val qu1 = scala.collection.immutable.Queue[Int](1,2,3,4,5)

val st2 = scala.collection.mutable.Stack[Int](1,2,3,4,5)

val qu2 = scala.collection.mutable.Queue[Int](1,2,3,4,5)

---------------------------------------------------

scala> val st1 = scala.collection.immutable.Stack[Int](1,2,3,4,5)
st1: scala.collection.immutable.Stack[Int] = Stack(1, 2, 3, 4, 5)

scala> val qu1 = scala.collection.immutable.Queue[Int](1,2,3,4,5)
qu1: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3, 4, 5)

scala> val st2 = scala.collection.mutable.Stack[Int](1,2,3,4,5)
st2: scala.collection.mutable.Stack[Int] = Stack(1, 2, 3, 4, 5)

scala> val qu2 = scala.collection.mutable.Queue[Int](1,2,3,4,5)
qu2: scala.collection.mutable.Queue[Int] = Queue(1, 2, 3, 4, 5)


---------------------------------------------------


scala> val list = List(1,2,3,4,5)
list: List[Int] = List(1, 2, 3, 4, 5)

scala> val list = List[Int](1,2,3,4,5)
list: List[Int] = List(1, 2, 3, 4, 5)

scala> val seq = Seq[Int](1,2,3,4,5)
seq: Seq[Int] = List(1, 2, 3, 4, 5)

scala> val set = Set[Int](1,2,3,4,5)
set: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4)

scala> val vec = Vector[Int](1,2,3,4,5)
vec: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4, 5)

scala> val str = Stream[Int](1,2,3,4,5)
str: scala.collection.immutable.Stream[Int] = Stream(1, ?)


---------------------------------------------------

val list = List(1,2,3,4,5)

or

val list = 1 :: 2 :: 3 :: 4 :: 5 :: Nil

or

val list = 1 :: (2 :: (3 :: (4 :: (5 :: Nil))))

---------------------------------------------------

scala> val list = List(1,2,3,4,5)
list: List[Int] = List(1, 2, 3, 4, 5)

scala> val list = 1 :: 2 :: 3 :: 4 :: 5 :: Nil
list: List[Int] = List(1, 2, 3, 4, 5)

scala> val list = 1 :: (2 :: (3 :: (4 :: (5 :: Nil))))
list: List[Int] = List(1, 2, 3, 4, 5)

---------------------------------------------------

scala> var list = List(4,5,6)
list: List[Int] = List(4, 5, 6)

scala> list :+ 7
res0: List[Int] = List(4, 5, 6, 7)

scala> 3 +: list
res1: List[Int] = List(3, 4, 5, 6)

---------------------------------------------------

var list = List(4,5,6)

list = 3 +: list

list = list :+ 7

list = 2 +: list :+ 8

---------------------------------------------------
scala> var list = List(4,5,6)
list: List[Int] = List(4, 5, 6)

scala> list = 3 +: list
list: List[Int] = List(3, 4, 5, 6)

scala> list = list :+ 7
list: List[Int] = List(3, 4, 5, 6, 7)

scala> list = 2 +: list :+ 8
list: List[Int] = List(2, 3, 4, 5, 6, 7, 8)

---------------------------------------------------

val list1 = List(1,2,3,4,5)

val list2 = List(6,7,8,9,10)

---------------------------------------------------

scala> val list1 = List(1,2,3,4,5)
list1: List[Int] = List(1, 2, 3, 4, 5)

scala> val list2 = List(6,7,8,9,10)
list2: List[Int] = List(6, 7, 8, 9, 10)

scala> val list3 = list1 +: list2
list3: List[Any] = List(List(1, 2, 3, 4, 5), 6, 7, 8, 9, 10)

scala> val list3 = list2 +: list1
list3: List[Any] = List(List(6, 7, 8, 9, 10), 1, 2, 3, 4, 5)

scala> val list3 = list1 :+ list2
list3: List[Any] = List(1, 2, 3, 4, 5, List(6, 7, 8, 9, 10))

scala> val list3 = list1 ::: list2
list3: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

---------------------------------------------------
Functions in Scala:
---------------------------------------------------
1. anaonymus functions
2. named functions
3. curried functions
---------------------------------------------------


1. anaonymus functions
---------------------------------------------------
(x : Int, y : Int) => x + y

val add = (x : Int, y : Int) => x + y

add(1,2)

---------------------------------------------------

scala> (x : Int, y : Int) => x + y
res2: (Int, Int) => Int = <function2>

scala> val add = (x : Int, y : Int) => x + y
add: (Int, Int) => Int = <function2>

scala> add(1,2)
res3: Int = 3


2. named functions
---------------------------------------------------

def add(x : Int, y : Int) = x + y

add(1,2)

---------------------------------------------------

scala> def add(x : Int, y : Int) = x + y
add: (x: Int, y: Int)Int

scala> add(1,2)
res4: Int = 3


3. curried functions
---------------------------------------------------

def add(x : Int)(y : Int) = x + y

add(1)(2)

---------------------------------------------------

scala> def add(x : Int)(y : Int) = x + y
add: (x: Int)(y: Int)Int

scala> add(1)(2)
res5: Int = 3

---------------------------------------------------

`named functions` importance
---------------------------------------------------

def add(x : Int, y : Int) = x + y

def add(x : Int = 1, y : Int = 2) = x + y

---------------------------------------------------

scala> def add(x : Int = 1, y : Int = 2) = x + y
add: (x: Int, y: Int)Int

scala> add()
res6: Int = 3

scala> add(10)
res7: Int = 12

scala> add(10,20)
res8: Int = 30

scala> add(x = 10, y = 20)
res9: Int = 30

scala> add(y = 20, x = 10)
res10: Int = 30

---------------------------------------------------
factorial of n:
---------------------------------------------------

def factorial(n : Int) = {
 if(n == 1) 1
 else n * factorial(n-1)
}

scala> def factorial(n : Int) = {
     |  if(n == 1) 1
     |  else n * factorial(n-1)
     | }
<console>:13: error: recursive method factorial needs result type
        else n * factorial(n-1)
                 ^

---------------------------------------------------

def factorial(n : Int) : Int = {
 if(n == 1) 1
 else n * factorial(n-1)
}

---------------------------------------------------
scala> def factorial(n : Int) : Int = {
     |  if(n == 1) 1
     |  else n * factorial(n-1)
     | }
factorial: (n: Int)Int

scala> factorial(5)
res11: Int = 120

scala> factorial(4)
res12: Int = 24

---------------------------------------------------
Object Oriented Programming in Scala
---------------------------------------------------
trait
abstract class
class
object
case class
---------------------------------------------------

case class A (a :Int, b : String) {
 override def toString() : String = s"a is $a, b is $b"
}
---------------------------------------------------
scala> case class A (a :Int, b : String) {
     |  override def toString() : String = s"a is $a, b is $b"
     | }
defined class A

scala> A(1, "kalyan")
res13: A = a is 1, b is kalyan

scala> new A(1, "kalyan")
res14: A = a is 1, b is kalyan

scala> val a1 = A(1, "kalyan")
a1: A = a is 1, b is kalyan

scala> val a2 = new A(1, "kalyan")
a2: A = a is 1, b is kalyan

--------------------------------------------------
class B (a :Int, b : String) {
 override def toString() : String = s"a is $a, b is $b"
}

---------------------------------------------------

scala> class B (a :Int, b : String) {
     |  override def toString() : String = s"a is $a, b is $b"
     | }
defined class B

scala> B(1, "kalyan")
<console>:12: error: not found: value B
       B(1, "kalyan")
       ^

scala> new B(1, "kalyan")
res16: B = a is 1, b is kalyan

scala> val b1 = new B(1, "kalyan")
b1: B = a is 1, b is kalyan



---------------------------------------------------
Share this article with your friends.
Related Posts Plugin for WordPress, Blogger...