
In this tutorial we,ll go through how to install SCALA in windows step by step.Here we will first check if Java already installed in our system or not.Because to run SCALA we must install JDK.We,ll check it by the command / > java - version.
Installation on Windows
Step 1: Verify the JDK installation on your machine. Open the shell/terminal and type java -version
Step 2: Download Scala binaries in the system from http://www.scala-lang.org/download/ and download the file
Step 3: Click on next button
Step 4: Select the terms in the licence agreement.Press next
Step 5: Select the folder where you want to install it and click on next.
Step 6: Click on install button
Step 7: Click on finish button
Step 8: You can check in the command prompt that SCALA is installed or not
In this tutorial we,ll go through how to install SCALA in windows step by step.Here we will first check if Java already installed in our system or not.Because to run SCALA we must install JDK.We,ll check it by the command / > java - version.
Installation on Linux
Step 1: Verify the JDK installation on your machine. Open the shell/terminal and type java -version
Step 2: Download Scala binaries using the command .You should be getting downloaded file as scala-2.11.8.tgz. Unzip the scala-2.11.8.tgz file using the following command as shown below.
Step 3: Download Scala binaries in the system from http://www.scala-lang.org/download/ and write click on it and copy link adress
Step 4: Go to the linux command prompt.Create seperate linux installatuon director lke mkdir scala.Then paste the link address here and the downloading is started.
Step 5:Unzip the downloaded zipped command by using this command line
Step 6: Update bashrc file manually with SCALA_HOME and PATH.Use the following command for unzipping
Step 7: Choose the scala parameters from the bashrc file and change the saving path from work to scala
Step 8: You can check in the command prompt that SCALA is installed or not
Basic Overview of Scala
Scala is a pure object-oriented language in the sense that every value is an object. Types and behavior of objects are described by classes and traits.
Scala has two ways for storing of data:
Mutable (var)
Immutable (val)
You can use var for a variable declaration in Scala. The main feature of var is that you can reassign values to it, after the first declaration. Because of this, such variables are called mutable – their values can be changed.
Opposite to var variables, with the help of val you can declare values which can’t be reassigned. Once you declare a val, you will not be able to change its value in the future. So think about val like about a constant. That’s why they are called immutable.
By This Command You Can Practice The Upper Mentioned Program
scala> val x: Int = 5
x: Int = 5
Literals
Literals are case insencitive.A literal (or literal data) is data that appears directly in the source code, like the number 5, the character A, and the text “Hello, World.”
By This Command We Can Perform The Function
scala> 5
res0: Int = 5
scala> 'A'
res1: Char = A
scala> "Hello"
rest2: String = Hello
scala>(x: Int) => x + 2
res3: Int => Int = <function1>
scala> vat str ="Hello"
scala>str
res4:String = Hello
str: String = Hello
scata> println(s"$str")
Hello
scata> println(s"$str James")
Hello James
Literals are often used as anonymous values that is, without bounding them to a named variable first.
In this solution, the code is a function literal (also known as an anonymous function):
Value
A value is an immutable, typed storage unit. A value can be assigned data when it is defined, but can never be reassigned.
Command for practice
scala> str
res4: String = Hello
scala> println(s"Sstr")
Hello
scala> println(s"$str James")
Hello James
scala> 5L
res7: Long = 5
scala> 6f
res8: Float = 6.0
scala> vat x:Int = 5
x: Int = 5
scala> vat y:Int = 6
y: Int = 6
scala> x * Y
<console>:13: error: not found: value Y
x * Y
ᐱ
scala> x * y
res10: Int = 30
scala> val c = x * y
c: Int = 30
scala> vat d = res10 +c
d: Int = 60
scala> a
<console>:12: error: not found: value a
a
ᐱ
scala> c
res12: Int = 30
scala> val e:Int = 10
e: Int = 10
scala> val f:Int = "hello"
Immutable collections, by contrast, never change. You have still operations that simulate additions, removals, updates, Nit those operations will in each case return a new collection and leave the old collection unchanged.
Scala Variables
A variable is a mutable, typed storage unit. A variable can be assigned data when it is defined and can also be reassigned data at any time.
By This Command You Can Practice The Function
scala> var:Int = 5
<console>:1: error: illegal start of simple pattern
var:Int = 5
ᐱ
scala> var x:Int = 5
x: Int = 5
scala> x = 10
x: Int = 10
scala> x
res15: Int = 10
scala> x = 5
x: Int = 5
scala> x
res16: Int = 5
scala> x = 5.5
<console>:12: error: type mismatch;
found : Double(5.5)
required: Int x = 5.5
ᐱ
scala> var x:Double = 5.5
x: Double = 3.5
scala> x = 5
x: Double = 5.0
Scala Types
Any is the supertype of all types, also called the top type. It defines certain universal methods such as equals, hashCode, and toString. Any has two direct subclasses: AnyVal and AnyRef.
AnyVal represents value types. There are nine predefined value types and they are non-nullable: Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean. Unit is a value type which carries no meaningful information. There is exactly one instance of Unit which can be declared literally like so: (). All functions must return something so sometimes Unit is a useful return type.
AnyRef represents reference types. All non-value types are defined as reference types. Every user-defined type in Scala is a subtype of AnyRef.
By This Command You Can Practice The Function
scala> x
res16: Int = 5
scala> x = 5.5
<console>:12:
error: type mismatch;
found : Double(5.5)
required: Int
x = 5.5
ᐱ
scala> var x:Double = 5.5
x: Double = 5.5
scala> x = 5
x: Double = 5.0
scala> val x = 59
x: Int = 59
scala> var x = 59
x: Int = 59
scala> x = 3.6 <consote>:12: error: type mismatch;
found : Double(3.6)
required: Int
x = 3.6
ᐱ
scala> var y:Double = 4.6
y: Double = 4.6
scala> y = 4
y: Double = 4.0
scala> y
res17: Double = 4.0
scala> val x:Int = 5
x: Int = 5
scala> val y:Float = x
y: Float = 5.0
scala> val z:Int = y
<console>:13: error: type mismatch;
found : Float
required: Int
val z:Int = y
ᐱ
scala> val z:Int = y.toInt
z: Int = 5
scala> var x = (5==6)
x: Boolean = false
scala> var x = (6==6)
x: Boolean = true
scala> var x = (6>6)
x: Boolean = false
scala> var x = (16>6)
x: Boolean = true
scala> var x =’a’
x:Char = a
scala> var x:Int =’a’
x:Int = 97
scala> var x:Int =’a’+5
x:Int = 102
If Else Expression:
In Scala an if statement can be followed by an else statement which gets executed when the if condition is false. If the boolean expression is true the if block statements are executed else if the if condition returns false the statements in the else block gets executed.
An 'if' statement can be followed by an optional 'else if...else' statement, which is very useful to test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
An 'if' can have zero or one else's and it must come after any else if's.
An 'if' can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of he remaining else if's or else's will be tested.
If..Else Expression Blocks
If Expressions
--------------------------------------------------------------------------------
if (<Boolean expression>) <expression>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
scala> if ( 47 % 3 > 0 ) println("Not a multiple of 3")
Not a multiple of 3
--------------------------------------------------------------------------------
Syntax: If-Else Expressions
--------------------------------------------------------------------------------
if (<Boolean expression>) <expression>
else <expression>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
scala> val x = 10; val y = 20
x: Int = 10
y: Int = 20
scala> val max = if (x > y) x else y
max: Int = 20
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
scala> val result = if ( false ) "what does this return?"
result: Any = ()
--------------------------------------------------------------------------------
If else Statement with Match Condition
Match Expressions
The traditional “switch” statement is limited to matching by value, but Scala’s match
expressions are an amazingly flexible device that also enables matching such diverse
items as types, regular expressions, numeric ranges, and data structure contents.
--------------------------------------------------------------------------------
<expression> match {
case <pattern match> => <expression>
[case...]
}
--------------------------------------------------------------------------------
scala> val day = "MON"
day: String = MON
scala> val kind = day match {
| case "MON" | "TUE" | "WED" | "THU" | "FRI" => "weekday"
| case "SAT" | "SUN" => "weekend"
| }
If else Statement With Value Binding Pattern
case <identifier> => <one or more expressions>
--------------------------------------------------------------------------------
scala> val day = "MON"
day: String = MON
scala> val kind = day match {
| case "MON" | "TUE" | "WED" | "THU" | "FRI" => "weekday"
| case "SAT" | "SUN" => "weekend"
Case other =>”Keyword not found”
| }
If else Statement with Wildcard Operator
===== Matching with Wildcard Patterns
There are two kinds of wildcard patterns you can use in a match expression
Variable Binding and underscore
--------------------------------------------------------------------------------
case_ => <one or more expressions>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
scala> val day = "MON"
day: String = MON
scala> val week = day match {
| case "MON" | "TUE" | "WED" | "THU" | "FRI" => "weekday"
| case "SAT" | "SUN" => "weekend"
Case_ =>”Keyword not found”
| }
--------------------------------------------------------------------------------
Matching with Pattern Guards
Syntax: A Pattern Guard case <pattern> if <Boolean expression> => <one or expressions>
val leave = 15
val week = leave match{
case s if s<15 => "Paid Leave" case s if s>=15 => "Casual Leave"
case s => "Not Applicable"
}
For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. There are various forms of for loop in Scala
In scala, for loop is known as for-comprehensions. It can be used to iterate, filter and return an iterated collection. The for-comprehension looks a bit like a for-loop in imperative languages, except that it constructs a list of the results of all iterations.
Syntax
for (<identifier> <- <iterator>) [yield] [<expression>]
For(i<-1 until 9) yield (i)
For Loop Iterator Guard
Iterator Guards
--------------------------------------------------------------------------------
for (<identifier> <- <iterator> if <Boolean expression>) ...
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
scala> val threes = for (i <- 1 to 20 if i % 3 == 0) yield i
For(i<-1 until 9 if i ≤ 5) yield (i)
For Loop Nested Iterator
Nested Iterators
Nested iterators are extra iterators added to a for loop,multiplying the total number of iterations by their iterator count.
Syntax
--------------------------------------------------------------------------------
scala> for { x <- 1 to 2
| y <- 1 to 3 }
| { print(s"($x,$y) ") }
(1,1) (1,2) (1,3) (2,1) (2,2) (2,3)
scala>
--------------------------------------------------------------------------------
Scala String
Scala - Strings. This chapter takes you through the Scala Strings. In Scala, a string is an immutable object, that is, an object that cannot be modified. Each element of a string is associated with an index number.
scala>var s:String ="Hello World"
s: String =
Hello World
scala> var q = "Hello World \n this is good morning"
q: String =
Hello World
this is good morning
Introduction to Procedure Study Note
Procedures A procedure is a function that doesn't have a return value. Any function that ends with a statement, such as a println() call, is also a procedure.
def log(d: bauble) = println(f"Got value $d%.2f")
def log(d: Double): Unit = println(f"Got value $d70.2f")
Nested Function
Nested Functions A function defined inside another function called Nested function. In Scala it is possible to nest function definitions.
Scala allows you to define functions inside a function and functions defined inside other functions are called local functions. Here is an implementation of a factorial calculator, where we use a conventional technique of calling a second, nested method to do the work.
def minx: Int, y: Id, z: Int) = {
def mininsisie(i: Int, j:Int) = if (i< j) i else j mininside
(x,mininside(y,z))
}
Partially Applied Function
Typically in function requires all of the parameters in t invocation. When give only a subset of the parameters to the function, the result of the expression is a partially applied function.
def totalsalary(basicant, variableSal:Int) =
{
basic + variableSal
}
val emplsalary .7: totalsalary(450, 234)
val commonsal = totalsalary(450, _:Int)
val emp2salary = commonsal(250)
val emp3salary :: commonsal(200)
Scala Programming Practices
There are two ways to create launching point for your application: define an object that extends the App trait.
OR
define an object with a properly defined main method.
Syntax
object Hello extends App {
printIn("Hello, world")
}
object Hello2 {
def main(args: Array[String]) {
printIn("Hello, world") }
}
in both cases, Scala applications are launched from an object, not a class.
Scala has a high-performance, object-oriented, and type-parameterized collections framework just as Java does. However, Scala's collections also have higher-order operations like map, filter, anti reduce.
Let's start with the List type, an immutable linked list. You can create a list by invoking it function, passing in its contents in the form o comma-separated parameters:
scala> val numbers = List(32, 95, 24, 21, 17)
scala> val colors = List("red", "green", "blue")
The size method, available on all collections and String instances, returns the number of items in the collection.
scala> println(s"I have ${colors.size} colors: $colors”
Collections are also type-parameterize ensuring that they remember and adhe the type they were initialized with.
scala> val colors = List("red", "green", "blue")
colors: List[String] = List(red, green, blue)
Use the Lisp-style head() and tail() methods to access the first and remaining elements of a list, respectively.
scala> colors.head
scale> colors.tai I
A Set is an immutable and unordered collection of unique elements, but works similarly to List. Sets are Iterable That contain no duplicate elements. Here is an example of creating a Set with duplicate items.
scale> val unique = Set(10, 20, 30, 20, 20, 10)
scala> var total = 0; for (i <- unique) ( total += i }
scala> unique(10)
Reducing List Generic
Scala's collections support
mathematical reduction operations, Boolean reduction operations and generic higher-order operations.
All list reductions use logic to reduce a list down to a single value.
The three folding operations, fold, reduce, and scan.
Reduces the list given a starting value and a reduction function.
fold - List(4, 5, 6).fold(0)(_+ _)
Reduces the list from left to right given a starting value and a reduction function.
foldLeft - List(4, 5, 6).foldLeft(0)(_+ _)
Reduces the list from right to left given a starting value and a reduction function.
foldRight - List(4, 5, 6).foldRight(0)(_+ _)
Reducing List Generic
Scala's collections support
mathematical reduction operations, Boolean reduction operations and generic higher-order operations.
All list reductions use logic to reduce a list down to a single value.
The three folding operations, fold, reduce, and scan.
Reduces the list given a starting value and a reduction function.
fold - List(4, 5, 6).fold(0)(_+ _)
Reduces the list from left to right given a starting value and a reduction function.
foldLeft - List(4, 5, 6).foldLeft(0)(_+ _)
Reduces the list from right to left given a starting value and a reduction function.
foldRight - List(4, 5, 6).foldRight(0)(_+ _)
Scala Collection Reduce List
List reduction is a common operation for working with collections. Let's look at ways to shrink down all that work to a single value, an action known as reducing a list. Scala's collections support mathematical reduction operations, Boolean reduction operations and generic higher-order operations.
Mathematical reduction operations
Finds the maximum value in the list.
max - List(41, 59, 26).max
Finds the minimum value in the list.
min - List(10.9, 32.5, 4.23, 5.67).min
Multiplies the numbers in the list.
product - List(5, 6, 7).product
Sums up the numbers in the list.
sum - List(11.3, 23.5, 7.2).sum
Boolean reduction operations
Checks if the list contains this element.
contains - List(34, 29, 18) contains 29
Checks if the list ends with a given list.
endsWith - List(0, 4, 3) endsWith List(4, 3)
Checks if a predicate holds true for at least one element in the list.
exists - List(24, 17, 32) exists L < 18)
Checks if a predicate holds true for every element in the list.
forall - List(24, 17, 32) forall (_ < 18)
Tests whether the list starts with a given list.
starts With - List(0, 4, 3) startsWith List(0)
Mapping List
Map
In set theory, and the field of mathematics in general, to map is to create an association between each element in one set to each element in another set.
Scala have map methods that take a function and apply it to every member of a list, collecting the results into a new list.
The map methods in List are doing mapping each item from one list t another list, so that the other list the same size as the first but with different data or element types.
val x = List(1,2,3,4,5,6,7,8,9)
x.map(a => a*a)
x.map(a => a+100)
flatMap
The flatMap method acts as a shorthand to map a collection and then immediately flatten it. flatMap = map + flatten
val fruits = Seq("apple", "banana", "orange")
fruits.map(_.toUpperCase)
fruits.flatMaP(_.toUpperCase)
Using a list of Options with map and flatMap
show more differences between map and flatMap for a simple String to Int conversion example
val mapResult rbstrings.map(toInt)
val flattenResult = mapResult.flatten
strings.flatMap(toInt)
strings.flatMap(toInt).sum
flatMap with another function
def g(v:Int) = List(v-1, v, v+1)
val a = g(2)
val list = List(1,2,3,4,5)
list.map(x => g(x))
Iist.flatMap(x => g(x))
Class and Inheritance on Scala
Scala Inheritance. Inheritance is an object oriented concept which is used to reusability of code. You can achieve inheritance by using extends keyword. To achieve inheritance a class must extend to other class.
If you remember the tutorial on Scala programming language, Scala is both an Object Oriented and Functional programming language. As a result of this Object Oriented nature, it has full support of object hierarchies through the use of class inheritance.
Classes are the core building block of object-oriented languages, a combination of data structures with functions ("methods"). A class defined with values and variables can be instantiated as many times as needed, each one initialized with its own input data.
// Simple class definition class User ( val name: String = "James" def greet: String = s"Hello from $namen
}
// Class with parameter class User (val name: String)( def greet: String = s"Hello from $name"
Scala Inheritance
Inheritance is an object oriented concept which is used to reusability of code. You can achieve inheritance by using extends keyword. To achieve inheritance a class must extend to other class.
A class which is extended called super or parent class. a class which extends class is called derived or base class.
If you remember the tutorial on Scala programming language, Scala is both an Object Oriented and Functional programming language.
As a result of this Object Oriented nature, it has full support of object hierarchies through the use of class inheritance.
A class which is extended called super or parent class. a class which extends class is called derived or base class.
When a class inherits from another, it extends another. We need to use the 'extends' keyword for this. This lets a class inherit members from the one it extends and lets us reuse the code.
// Simple class definition class User ( val name: String = "James" def greet: String = s"Hello from $namen
}
// Class with parameter class User (val name: String)( def greet: String = s"Hello from $name"
Reducing List Generic
Scala's collections support
mathematical reduction operations, Boolean reduction operations and generic higher-order operations.
All list reductions use logic to reduce a list down to a single value.
The three folding operations, fold, reduce, and scan.
Reduces the list given a starting value and a reduction function.
fold - List(4, 5, 6).fold(0)(_+ _)
Reduces the list from left to right given a starting value and a reduction function.
foldLeft - List(4, 5, 6).foldLeft(0)(_+ _)
Reduces the list from right to left given a starting value and a reduction function.
foldRight - List(4, 5, 6).foldRight(0)(_+ _)
Abstract Classes and Traits
Scala has traits, and a trait is more flexible than an abstract class, So the question arise in this case that “When should we use an abstract class?”
There are two main reasons to use an abstract class in Scala
1.When you want to create a base class that requires constructor arguments.
2.The code will be called from Java code.
A class can extend one superclass, and thus, only one abstract class. A trait is restricted in comparison to classes in that it cannot have constructor parameters
The restrictions of traits in comparison to classes are introduced to avoid typical problems with multiple inheritance.
There are more or less complicated rules with respect to the inheritance hierarchy; it might be best to avoid a hierarchy where this actually matters. It can only matter if we inherit two methods with the same signature or two variables with the same name from two different traits.
Case Classes
Case classes are like regular classes but have few key differences. Case classes are good for modeling immutable data.
Scala supports the notion of case classes. Case classes export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching.
A scala case class also has all vals, which means they are immutable.
To define a minimal Scala Case Class, we need the keywords ‘case class’, an identifier, and a parameter list. We can keep the parameter list empty.
You can create a (shallow) copy of an instance of a case class simply by usng the copy method.
val message5 = message4.copy(sender = message4.recipient,
recipient = "claire@bourgogne.fr")
The recipient of message4 is used as the sender of message5 but the body of message4 was copied directly.
In this course you are going to learn Scala Programming. The course is designed to the point and from very beginning. This course is Totally for the Beginners Who do not have any concept in Scala. After completing this course you get a basic overview about Scala Programming.
Scala is one of the Hot Demanding Language in 2017!
The language is introduce by Martin Odersky in 2003.
This Series explains Scala Programming in the User Friendly and Easy to understand Way!
Here In this course we start form very basic Scala Setup and then We move to the Variables, Literals, Strings any Other Advance Concepts.If you do not have any knowledge in Scala that is O. K. We Guide you from the very basic step to the advance concepts.
If you have knowledge in Programming Language like C++, Java You get an additional Benifit.