Declaring variables
1. Immutable variables
We can't change value of Immutable variables in our code. If try to
change immutable variable value then scala complier give error while
execution. To define immutable variable, we use the keyword val.
Syntax: val <Name of our variable>:<Scala
datatype>=<literals>
2. Mutable variables
We can change value of mutable variables in our code. To define mutable
variable, we use the keyword var.
Syntax: var <Name of our variable>:<Scala
datatype>=<literals>
3. Lazy initialization
Sometimes you may wish to delay the initialization of
some variable until at the point where it is consumed by your
application. This is usually referred to as lazy initialization and we need to
make use of the lazy keyword
Syntax: lazy var <Name of our variable>:<Scala
datatype>=<literals>
4. Scala Supported Types
val bookPrice: Int = 5
val bigNumberPathCode: Long = 100000000L
val smallNumberPAthCode: Short = 1
val priceOfBook: Double = 2.50
val bookPrice: Float = 2.50f
val deptStoreName: String = "allabout books"
val macByte: Byte = 0xa
val gearFirstLetter: Char = 'G'
val nothing: Any = //Accept any datatype
5. Declare a variable with no initialization
Sometimes you may not know the value of your variable immediately. You
can only assign your variable's value at some later point in time during the
execution of your application.
var favoriteFood: String = _ //wildcard
operator _ when defining variable
favoriteFood= "Pizza"
favoriteFood= "Pizza"
String interpolation
String
interpolation to print a variable
Let's
assume that you have a variable called fDoInterpolation and would
like to use the String interpolation feature in Scala to print that variable
Eg:
println("Step
1: String interpolation to print a variable")
val
fDoInterpolation: String = "Interpolation"
println(s"My
string = $fDoInterpolation")
NOTE:
1. We've prefixed the s at the beginning of
our println statement.
2. We also used the dollar sign $ to refer to our
variable.
Using String interpolation on object properties
We have an object which represents a donut and it
has name and PLevel properties. We can represent this
DInter object using a case class:
println("\nStep 2: Using String interpolation
on object properties")
case class DInter(name: String, PLevel:
String)
val fDInter: DInter = DInter("Glazed Donut", "Very Tasty")
println(s"fDInter name = ${fDInter.name},
tasteLevel = ${fDInter.PLevel }")
Using f interpolation to format numbers
we wanted to print the 2 decimal places for the bookPrice variable. This
can be achieved by using the f interpolator
println("\nStep 5: Using f interpolation to format numbers")
val bookPrice: Double = 2.50
println(s"Book price = $bookPrice")
println(f"Formatted book price = $bookPrice%.2f")
Using backslash to escape quotes
Escaping quotes in a String using backslash \
Eg:
println("\nStep
2: Using backslash to escape quotes")
val
bsJson2: String
="{\"book_name\":\"Gladiator\",\"b_level\":\"Hard\",\"price\":26.50}"
println(s"bsJson2
= $bsJson2")
Using triple quotes """ to escape characters
Eg:
val
bsJson2: String =
"""{"book_name":"Gladiator","b_level":"Hard","price":25.50}"""
println(s"bsJson2
= $bsJson2")
Output :
Using
triple quotes """ to escape characters
bsJson2 =
{"book_name":"Gladiator","b_level":"Hard","price":25.50}
How To Use IF Else Statement And Expression
In Scala, you can use the if and else clause as a statement to
test for some condition or logical step.
Eg:
var a:Int
= 90
var
b:Int = 87
var
c:Int = 120
if
( (a > b) && (a > c) )
{
println ("a is greater")
}
else if (
(b > a) && (b > c) )
{
println ("b is greater")
}
else
{
println ("c is greater")
}
How To Use For Comprehension
A simple
for loop by iterating from 0 to 4 and print the immutable variable i during
each iteration.
var
test_sum = 0
for(i<-0
to 4){
test_sum
+= i
}
println(test_sum)
Used of
keyword until which meant that the iteration number 5 was not included.
var
test_sum = 0
for(i<-0
to 5)
{
test_sum
+= i
}
println(test_sum)
Use of Range
val
from1To5 = (1 to 5 by 2).toList
println(from1To5)
Output:
List(1,3,5)
val
from1To5 = (1 to 5).toList
println(from1To5)
Output:
List(1,2,3,4,5)
//toSet,
toSeq & toArray
Calling
the .mkString() function to create a string representation of each collection
type.
The
.mkString() function takes in a delimiter which in our case is just an empty
space.
Use of
while loop in Scala
Let's
declare a mutable variable called num
var
num:Int = 5
while(num>0)
{
println(num)
num -= 1
}
Use of do
while loop in Scala
The
difference between a while construct from Step 1 versus a do while is that any
expressions within the do {} will be ran at least once regardless of the
condition within the while() clause.
println("Use
of do while loop in Scala")
var i = 0
do {
i
+= 1
println("Number start from = " + i)
} while
(i < 5)
Use
Pattern Matching
Pattern
matching
Suppose
you want to test a variable called foodType. In the case that its value is Veg
Food, you will print Very Tasty. On the other hand, if its value is NonVeg
Food, then you will print Tasty.
println("Pattern
matching")
val
foodType = "Veg Food"
foodType
match {
case "Veg Food" => println("Very tasty")
case "NonVeg Food" => println("Tasty")
}
Create
And Use Enumerations (enum)
Create an
Enumeration
Let us
extend the Enumeration class and create an enumeration to represent flavour.
println("Step
1: How to create an enumeration")
object
Flavour extends Enumeration {
type Flavour = Value
val Lichi = Value("Lichi")
val Strawberry = Value("Strawberry")
val Plain = Value("Plain")
val Vanilla = Value("Vanilla")
}
Print the
String value of the enumeration
We would
like to print the String value for the Vanilla element.
println("Print
the String value of the enumeration")
println(s"Vanilla
Flavour string value = ${Flavour.Vanilla}")
Print the
String value of the enumeration
Vanilla
Flavour string value = Vanilla
Print the
id of the enumeration
First
need to navigate down to the Vanilla element and then call the id function.
println("Print
the id of the enumeration")
println(s"Vanilla
Flavour's id = ${Flavour.Vanilla.id}")
Vanilla
Flavour's id = 3
No comments:
Post a Comment