Introduction to Scala
Why Scala?
Scala is multi paradigms, it is object-oriented, functional, type-safe, runs on Java Virtual Machine (JVM), immutable oriented which makes it easy to write code with concurrency and parallelism (Synchronize). Scala is scalable and suitable for distributed systems. Scala lines of code are elegant and light because it is functional and uses only expressions without any details with many possibilities to define the anonymous and nested function.
There are two main paradigms, Imperative and Declarative. Imperative languages use a sequence of statements in order to accomplish a purpose, therefore lines of code grow more than functional ones.
What is Functional Programming?
Functional programming is a subset of declarative programming and Object Oriented Programming is a subset of imperative languages. But why is functional programming on the cutting edge of technology? It is because of having efficient and reliable behavior when working with multiple processors or in better words, it has the best performance while working with parallel programming.
Installing Scala
- Download Suitable JDK according to an operating system (Linux macOS Windows)
https://www.oracle.com/technetwork/java/javase/downloads/index.html - Set Java Environment
Windows
Advanced system settings -> Environment Variables
Set var JAVA_HOME = C:\{Java Path}\java\jdk{version}
Set system var as Path = C:\{Java Path}\java\jdk{version}\bin
Linux: Terminal
Export JAVA_HOME=/usr/local/java{version}
Export PATH=$PATH:$JAVA_HOME/bin/
- Execute
java –version
in command prompt or terminal. - Download Suitable Scala according to operating system (Linux macOS Windows)
Download
Compared to other programming languages, installing Scala is a bit unusual. Scala is unusual because it is usually…www.scala-lang.org
Select intelliJ or SBT or other ways to install Scala and select for example, Download the Scala binaries for windows. You can also use:
Or you can use command prompt or terminal to run:
java –jar scala{version}-installer.jar
- Test by running scala –version if all is ok!
Scala Project
File -> New -> Project
Right click on the solution -> src -> New File
Some important facts which must be observed during the code:
- Object Name should be equal to this file name, otherwise, there are some difficulties to compile.
- Short keys to collapse all methods and classes: Crtl + Shift + -
- Short keys to unfold all methods and classes: Crtl + Shift + +
File -> Project Structures -> Libraries
Go to terminal and set your path to your Scala file:
C:\>cd C:\Users\Mahsa\ScalaIntro\src
C:\Users\Mahsa\ScalaIntro\src> scalac ScalaQuickStart.scala
C:\Users\Mahsa\ScalaIntro\src> scala ScalaQuickStart
Class — Object — File I/O — Exception Handling
import java.io._
import scala.io.Source
import java.io.FileNotFoundException
import java.io.IOException
import Array._
object ScalaQuickStart {
def main(args: Array[String]) {
var inc = (x:Int) => x+1
println(inc(2))
val rff = new ReadFromFile()
rff.read()
val wr = new WriteToFile()
wr.write()
var myMatrix = ofDim[Int](2, 2)
val bufferedSource = Source.fromFile("C:\\file\\grades.csv")
for (line <- bufferedSource.getLines) {
println(line)
val nums = line.split(",")
println(nums.head, nums.last)
}
}
class ReadFromFile() {
def read() {
try {
Source.fromFile("C:\\file\\grades.csv").foreach {
print
}
}
catch {
case ex: FileNotFoundException => {
println("Missing file exception")
}
case ex: IOException => {
println("IO Exception")
}
}
finally {
println("finally runs anyway...")
}
}
}
class WriteToFile() {
def write() {
try {
val writer = new PrintWriter(new File("C:\\file\\grades.txt"))
writer.write("Hello Scala")
writer.close()
}
catch {
case ex: FileNotFoundException => {
println("Missing file exception")
}
case ex: IOException => {
println("IO Exception")
}
}
}
}
class ProcessArray() {
def read() {
try {
Source.fromFile("C:\\file\\grades.csv").foreach {
print
}
}
catch {
case ex: FileNotFoundException => {
println("Missing file exception")
}
case ex: IOException => {
println("IO Exception")
}
}
finally {
println("finally runs anyway...")
}
}
}
}
Collection
Function
The most important reason why functional programming is on the cutting edge of technology is because of having efficient and reliable behavior when working with multiple processors or in better words, it has the best performance while working with parallel programming.
Avoiding Stack Overflow by Tail Call Optimization
Another reason is that loops and iterations in functional languages will be done via recursion with TCO (Tail Call Optimization). TCO is an approach to call the function without separated stack frames work and it avoids stack overflow. For example, in the below code, Factorial(4)
computation needs 4 separate stack frames while the next one in functional languages needs just one stack frame.
It is not TCO:
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
This is TCO:
def factorial(n):
return fact(n, 1)
def fact(n, number):
if n == 0:
return number
return fact(n-1, number*n)
Avoiding Race Condition and Deadlock by the Aid of Immutable Objects as Thread Safe
What Is the Race Condition?
In multi-threading concept, when two or more threads try to catch a shared resource or object at the same time.
What is Deadlock?
In multi-threading concept, when process 1 holds a locked resource 2 and waits for resource 1, while exactly at this time, process 2 holds and locks resource 1 and waits for resource 2.
What is Thread-safety?
In multi-threading concept, thread safe ensures that each thread can perform its execution properly in a simultaneously way without unintended interactions.
What is Immutable?
Immutable object's state or value cannot be changed after creation. a
is mutable because its value will be changed:
a = 1
b = 2
a = a + b
In creation time, a
should be defined as read-only and immutable to prevent change its value.
Conclusion
Because of immutable as thread safe in functional programming; it is useful for infinitive for
or foreach
loop — special in mathematic functions — and prevents race condition and Deadlock.
History
- 1st July, 2019: Initial version