You are on page 1of 71

Exploring SCALA

AMRITPAL SINGH
▪ If you ask any industry expert, what language should
you learn for big data, they would definitely suggest
you to start with Scala.

▪ Scala has gained a lot of recognition for itself and is


Get Started !! used by the large number of companies.

▪ Scala and Spark are being used at Facebook, Pinterest,


NetFlix, TripAdvisor for Big Data and Machine Learning
applications.
▪ Where to use Scala

▪ Data analysis with Spark


INTRODUCTION ▪ Parallel batch processing
▪ Web applications
▪ Utilities and libraries
▪ In Scala, you can create any type of application in less
time and coding whether it is web based, mobile based
INTRODUCTION or desktop based application.
▪ Lazy Computation
▪ In Scala, computation is lazy by default. Scala evaluates
expressions only when they are required. You can
declare a lazy variable by using lazy keyword. It is used
to increase performance.
Features of
Scala ▪ Type Inference
▪ In Scala, you don't require to mention data type and
function return type explicitly. Scala is enough smart to
deduce the type of data.
▪ In scala, everything is an object whether it is a function
or a number.

▪ File extension of scala source file may be either .scala


or .sc.
Features of
Scala ▪ Scala is a general-purpose programming language. It
supports object oriented, functional and imperative
programming approaches.
BASIC
OPERATIONS
BASIC
OPERATIONS
DATA
TYPES/COMMENTS
DATA TYPES
DATA TYPES
ARITHMETIC
OPERATORS
MATH
OPERATORS
MATH
OPERATORS
CONDITIONAL/LOGICAL
OPERATORS
IF/ELSE
▪ object ScalaExample{
▪ def main(args:Array[String]){
Scala Example: ▪ println "Hello Scala"
Hello Scala ▪ }
▪ }
▪ This program contains a method “main” (not returning
any value) which takes an argument – a string array
through command line. Next, it calls a predefined
method called “Println” and passes the argument

Scala Example: ▪ main method which should serve as the entry point for
an application.
Hello Scala
▪ In Java args contains the supplied command-line
arguments as an array of String objects.

▪ In other words, if you run your program as java


MyProgram one two then args will contain ["one", "two"]
▪ You can also use IDE (Integrated Development
Environment) for executing scala code.
Scala Example: ▪ The above example is written using object oriented
Hello Scala approach. You can also use functional approach to write
code in scala.
▪ def scalaExample{

Scala Example: ▪ println("Hello Scala")

▪ }
Hello Scala
▪ scalaExample // Calling of function
▪ object MainObject {
▪ def main(args: Array[String]) {

▪ var a = 1
▪ a match{

Scala Pattern ▪ case 1 => println("One")

▪ case 2 => println("Two")


Matching
▪ case _ => println("No")
▪ }

▪ }
▪ }
▪ Here, match using a variable named a.

Scala Pattern ▪ This variable matches with best available case and
prints output.
Matching
▪ Underscore (_) is used in the last case for making it
default case.
▪ while(boolean expression){
▪ // Statements to be executed
While loop ▪ }
▪ object MainObject {
▪ def main(args: Array[String]) {

▪ var a = 10; // Initialization


▪ while( a<=20 ){ // Condition
▪ println(a);
While loop ▪ a = a+2 // Incrementation
▪ }
▪ }

▪ }
▪ for( i <- range){

Scala for loop ▪ // statements to be executed

▪ }
▪ object MainObject {
▪ def main(args: Array[String]) {

▪ for( a <- 1 to 10 ){

Scala for loop ▪ println(a);


▪ }

▪ }
▪ }
▪ object MainObject {
▪ def main(args: Array[String]) {

▪ for( a <- 1 until 10 ){


Scala for loop ▪ println(a);
▪ }

▪ }
▪ }
▪ object MainObject {
▪ def main(args: Array[String]) {

▪ for( a <- 1 to 10 if a%2==0 ){


Scala for loop ▪ println(a);
▪ }

▪ }
▪ }
Scala for-loop in ▪ In scala, you can iterate collections like list, sequence
etc, either by using for each loop or for-
Collection comprehensions.
▪ object MainObject {
▪ def main(args: Array[String]) {

▪ var list = List(1,2,3,4,5,6,7,8,9) // Creating a list

Scala for- loop ▪ for( i <- list){ // Iterating the list


Example for ▪ println(i)

Iterating Collection ▪ }

▪ }

▪ }
▪ object MainObject {
▪ def main(args: Array[String]) {

▪ for(i<-1 to 10 by 2){
Scala for-loop
▪ println(i)
Example using by
▪ }
keyword
▪ }
▪ }
▪ object MainObject {
▪ def main(args: Array[String]) {

▪ functionExample() // Calling function


▪ }
▪ def functionExample() { // Defining a function
Functions
▪ println("This is a simple function")
▪ }
▪ }
▪ object MainObject {
▪ def main(args: Array[String]) = {

▪ functionExample(10,20)
▪ }
▪ def functionExample(a:Int, b:Int) = {
Functions ▪ var c = a+b
▪ println(c)
▪ }

▪ }
▪ Lists are one of the most versatile data structure in
Scala.

▪ Lists contain items of different types in Python, but in


Lists Scala the items all have the same type.

▪ Scala lists are immutable.


▪ scala> val numbers = List(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)

▪ Let’s get the third element of the list “numbers” . The


index should 2 because index in Scala start from 0.
Lists
▪ scala> numbers(2)
▪ res6: Int = 3
▪ In Scala, an array is a collection of similar elements.

Arrays in Scala ▪ It can contain duplicates.

▪ Arrays are also immutable in nature. Further, you can


access elements of an array using an index.
▪ To declare any array in Scala, you can define it either
using a new keyword or you can directly assign some
Arrays in Scala values to an array.
▪ var name = Array("Faizan","Swati","Kavya", "Deepak",
"Deepak")
Arrays in Scala
▪ In the above program, we have defined an array called
name with 5 string values.
▪ Declaring an array using “new” keyword

▪ var name:Array[String] = new Array[String](3)


▪ or
Arrays in Scala ▪ var name = new Array[String](3)
▪ Output:
▪ name: Array[String] = Array(null, null, null)
▪ Here you have declared an array of Strings called
“name” that can hold up to three elements.

▪ You can also assign values to “name” by using an index.


Arrays in Scala
▪ scala> name(0) = "A"
▪ scala> name(1) = "B"
▪ scala> name(2) = "C"
▪ Let’s print contents of “name” array.
Arrays in Scala
▪ scala> name
▪ Accessing an array

Arrays in Scala ▪ You can access the element of an array by index. Lets
access the first element of array “name”. By giving
index 0. Index in Scala starts from 0.
▪ The biggest difference is in the idea of direct access Vs
sequential access.

Arrays in Scala
▪ Arrays allow both; direct and sequential access, while
lists allow only sequential access.
▪ At first glance, a Scala String appears to be just a Java
String. For instance, when you work in the Scala Read-
Evaluate-Print-Loop (REPL) environment and print the
Strings name of a String literal, the REPL feedback tells you the
type is java.lang.String.
▪ "Hello, world".getClass.getName
res0: String = java.lang.String

Strings ▪ Indeed, a Scala String is a Java String, so you can use all
the normal Java string methods.
Strings
▪ You can concatenate strings:
▪ val s ="Hello" + " world“

▪ These are all familiar operations.

▪ But because Scala offers the magic of implicit


Strings conversions, String instances also have access to all the
methods of the StringOps class, so you can do many
other things with them, such as treating a String
instance as a sequence of characters.

▪ As a result, you can iterate over every character in the


string using the foreach method
Strings
▪ Add Methods to Closed Classes

▪ scala> "scala".drop(2).take(2).capitalize
Strings
▪ Testing String Equality

▪ In Scala, you compare two String instances with the ==


Strings operator.
Strings
▪ Creating Multiline Strings

▪ In Scala, you create multiline strings by surrounding


your text with three double quotes:
Strings ▪ val b = """This is a
▪ multiline

▪ String"""
▪ Splitting Strings

▪ The split method returns an array of String elements,


which you can then treat as a normal Scala Array :
Strings ▪ scala> "hello world".split(" ").foreach(println)
▪ hello
▪ world
Substituting Variables into Strings

Strings :
String
interpolation
▪ scala> println(s"Age next year: ${age + 1}")
Age next year: 34
Strings : String
interpolation ▪ scala> println(s"You are 20 years old: ${age == 33}")
▪ You are 20 years old: false
Strings : String
interpolation
Strings
▪ Processing a String One Character at a Time

Strings ▪ You want to iterate through each character in a string,


performing an operation on each character as you
traverse the string
▪ scala> val upper = "hello, world".map(_.toUpper)
▪ upper: String = HELLO, WORLD

Strings ▪ scala> val upper = "hello, world".filter(_ !=


'l').map(_.toUpper)
▪ upper: String = HEO, WORD
▪ Regular expressions are pattern matching utilities
found in most of the programming languages. They
define a generic pattern to match a sequence of input
characters.

Strings ▪ Regex are widely used in text parsing and search.

▪ The Regex class in scala is available in


scala.util.matching package.
Strings

Finding Patterns in Strings


Replacing Patterns in Strings

Strings
▪ How to extract parts of a string that match a regex ?

▪ Define the regular-expression patterns you want to


extract from your String, placing parentheses around
Strings them so you can extract them as “regular-expression
groups.” First, define the desired pattern:
▪ val pattern = "([0-9]+) ([A-Za-z]+)".r

▪ Next, extract the regex groups from the target string:

▪ val pattern(count, match) = "100 ODI“

▪ This code extracts the numeric field and the alphabetic


field from the given string as two separate variables, count
Strings and match, as shown in the Scala REPL:

▪ scala> val pattern(count, match) = "100 ODI"


▪ count: String = 100
▪ match: String = ODI
Accessing a
Character in a
String
▪ val a=scala.io.StdIn.readInt()
Input from User ▪ println("The value of a is "+ a)
▪ def readBoolean(): Boolean Reads a Boolean value from
an entire line from stdin .

▪ def readChar(): Char Reads a Char value from an entire


line from stdin .

Input from User


▪ def readDouble(): Double Reads a Double value from an
entire line from stdin .

▪ def readFloat(): Float Reads a Float value from an entire


line from stdin .
▪ def readInt(): Int Reads an Int value from an entire line
from stdin .

Input from User ▪ def readLine(text: String, args: Any*): String Prints
formatted text to stdout and reads a full line from stdin .

▪ def readLine(): String Reads a full line from stdin .


▪ For each iteration of your for loop, yield generates a
value which will be remembered.

▪ It's like the for loop has a buffer you can’t see, and for
Scala for/yield each iteration of your for loop another item is added to
that buffer.

▪ When your for loop finishes running, it will return this


collection of all the yielded values.
▪ scala> for (i <- 1 to 5) yield i

▪ Nothing too exciting there, but it’s a start. Next, let’s


double every element in our initial collection:

Scala for/yield ▪ scala> for (i <- 1 to 5) yield i * 2

▪ scala> for (i <- 1 to 5) yield i % 2


▪ for-loop/yield examples over a Scala Array

▪ scala> val a = Array(1, 2, 3, 4, 5)


▪ a: Array[Int] = Array(1, 2, 3, 4, 5)

▪ scala> for (e <- a) yield e


Scala for/yield ▪ res5: Array[Int] = Array(1, 2, 3, 4, 5)

▪ scala> for (e <- a) yield e * 2


▪ res6: Array[Int] = Array(2, 4, 6, 8, 10)

▪ scala> for (e <- a) yield e % 2


▪ res7: Array[Int] = Array(1, 0, 1, 0, 1)

You might also like