Scala programming concept part one
GitHub Source Code
# Brief Introduction To Scala
Scala stands for “scalable language.” The language is so named because it was designed to grow with the demands of its users. You can apply Scala to a wide range of programming tasks, from writing small scripts to building large systems.
Scala is a blend of object-oriented and functional programming concepts in a statically typed language. The fusion of object-oriented and functional programming shows up in many different aspects of Scala; it is probably more pervasive than in any other widely used language. The two programming styles have complementary strengths when it comes to scalability. Scala’s functional programming constructs make it easy to build interesting things quickly from simple parts. Its object-oriented constructs make it easy to structure larger systems and adapt them to new demands. The combination of both styles in Scala makes it possible to express new kinds of programming patterns and component abstractions. It also leads to a legible and concise programming style.
Source : Scala Programming 5th Edition Book
By Martin Odersky
# Scala Variables
Scala Has Two Variables
var
Andval
‘val’ is immutable can’t be reassigned to new value example
val msg = "Hello, world!"
var
is the opposite it can be reassigned to new value through it’s lifetime as shown Below1 2
var greeting = "Hello, World!" greeting = "Hello My Name Is Mahmoud"
Scala is statically Typed but compiler can infer the Types
1 2 3 4 5 6 7 8 9 10 11 12 13 14
val aString: String = "hello" val aBoolean: Boolean = false val aChar: Char = 'a' val aShort: Short = 4613 val aLong: Long = 5273985273895237L val aFloat: Float = 2.0f //or without types val aString = "hello" val anotherString = "goodbye" val aBoolean = false val aChar = 'a' val aShort = 4613 val aLong = 5273985273895237L val aFloat = 2.0f
# Scala Function Definition And Syntax
|
|
def
== defining method ,biggerThan
== function name ,(x:Int,y:Int)
== parameter list in parentheses ,:Int
== function return type scala function must have a return type ,if x > y the x else Y
the body of the function1
def greet():Unit = println("Hello, world!")
def greet(): Unit. “greet” is, of course, the name of the function. The empty parentheses indicate the function takes no parameters. And Unit is greet’s result type. A result type of Unit indicates the function returns no interesting value. Scala’s Unit type is similar to Java’s void type; in fact, every void-returning method in Java is mapped to a Unit-returning method in Scala. Methods with the result type of Unit, therefore, are only executed for their side effects.
so What Are Side Effects?? A function has a side effect if it does something other than simply return a result, for example:
- Modifying a variable
- Modifying a data structure in place
- Setting a field on an object
- Throwing an exception or halting with an error
- Printing to the console or reading user input
- Reading from or writing to a file
- Drawing on the screen
Source Functional Programming in Scala Book (AKA The Red Book)
By Paul Chiusano and Runar Bjarnason
- we Will discuss later pure functional programming in depth in the upcoming articles
lets discuss a little exercise to gave you a taste of functional programming in scala this might be a little advanced for some but don’t worry all concepts mentioned below will be explained later in depth in the upcoming lectures
consider you have a collection of numbers you don’t know how large or small it’s and you only want to filter the even numbers before jumping into solution let’s think how to implement this example with optimal performance and minimal use of resources , now in functional programming we tell the (compiler) what to do unlike in imperative style of programming we tell the (compiler) step by step how to run the code and get the desired result so given what i have said above we will not use
var
or normalfor
orfor each
loops instead we will use for ComprehensionWhat is For Comprehension ?? has a
for
Enumeration over a given provided<-
in Collection withyield
keyword for each binding generated by the enumerators and returns a sequence of these values.Next What Type Of Collection To Choose ?? it’s obvious as we don’t know the size of the collection and we are using a Immutable Collection so for best given case to this example we will use a type of collection
LazyList
which is a linked list whose elements are lazily evaluate aLazyList
both the head and the tail are lazy , So What ISlazy
MEANS IN FIRST PLACE ?? in programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed.let me show you my solution below and see how expressive Scala is,as if it’s a natural language
1 2 3 4 5
object ScalaPartOne: def main(args: Array[String]):Unit= def aCollection(evenNum:LazyList[Int]):LazyList[Int]= for x <- evenNum if x % 2 == 0 yield x aCollection(LazyList(2,3,4,6,7)) foreach println
1 2 3 4
2 4 6 Process finished with exit code 0
- Another Solution Less Optimized For Large Collections but Shorter Syntax
1 2 3
val numbers: IndexedSeq[Int] = for i:Int <- 1 to 10 filter(_%2==0) yield i numbers foreach println println(numbers toList)
1 2 3 4 5 6
2 4 6 8 10 List(2, 4, 6, 8, 10)
- There is Also Recursion And Tail Recursion Will Be Explained In Detail In The Upcoming Lectures.
Functions in Scala is either Called By Name Or Called By Value according to given parameter
- Incase Called By value it’s normal parameter with given type Example:
1 2 3 4
def calledByValue(x: Long): Unit = println("by value: " + x) println("by value: " + x) calledByValue(1257387745764245L)
- Incase Called By Name the parameter inside the function is another high order function (discussed later) returns a given type Example:
1 2 3 4
def calledByName(x: => Long): Unit = println("by name: " + x) println("by name: " + x) calledByName(System.nanoTime())
Functions in Scala can have default parameter or parameters values hat can be used to allow a caller to omit those parameters
- Example:
1 2 3
def log(message: String, level: String = "INFO") = println(s"$level: $message") log("System starting") // prints INFO: System starting log("User not found", "WARNING") // prints WARNING: User not found
The parameter
level
has a default value so it is optional. On the last line, the argument"WARNING"
overrides the default argument"INFO"
. Where you might do overloaded methods in Java, you can use methods with optional parameters to achieve the same effect. However, if the caller omits an argument, any following arguments must be named.
# Scala’s Expressions, Statements, and Conditionals
Expressions indicates a unit of code that returns a value after it has been executed. One or more lines of code can be considered an expression if they are collected together,this is known as as expression block
Expressions provide a foundation for functional programming because they make it possible to return data instead of modifying existing data (such as a variable). This enables the use of immutable data, a key functional programming concept where new data is stored in new values instead of in existing variables. Functions, of course, can be used to return new data, but they are in a way just another type of expression.
When all of your code can be organized (or conceptualized) into a collection of one or more hierarchical expressions that return values using immutable data will be straightforward. The return values of expressions will be passed to other expressions or stored into values. As you migrate from using variables, your functions and expressions will have fewer side effects. In other words, they will purely act on the input you give them without affecting any data other than their return value. This is one of the main goals and benefits of functional programming..
Source: Learning Scala Book
OREILLY
Statements A statement is just an expression that doesn’t return a value. Statements have a return type of Unit, the type that indicates the lack of a value. Some common statements used in Scala programming include calls to println() and value and variable definitions.
Examples
val x = "hello"
This is an expressionAll operators are functional expressions in Scala like (+ - * / &)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
val x = 1 + 2 // EXPRESSION println(x) // 3 println(1 + 2 * 3) // 7 multiplication first then addition println((1+2)*3) //9 println(1 == x) //false println(!(1 == x)) //true //var with side effects var aVariable = 2 aVariable += 3 // also works with -= *= /= ..... side effects println(aVariable) //if expression val aCondition = true println(if aCondition then 5 else 3) //expression block val aCodeBlock = val y = 2 val z = y + 1 if z > 2 then "hello" else "goodbye"
# String Operations In Scala
String are immutable which means a constant and cannot be changed once created.
I recommend you to go and Read geeksforgeekspost they almost cover all
String
operation methods so check them outBut I will discuss here String interpolators types
- s-interpolators Prepending
s
to any string literal allows the usage of variables directly in the string Example:
1 2
val name = "James" println(s"Hello, $name") // Hello,James
- f-Interpolator
Prepending
f
to any string literal allows the creation of simple formatted strings, The f interpolator is typesafe. If you try to pass a format string that only works for integers but pass a double, the compiler will issue an error Example:
1 2 3
val height = 1.9d val names = "James" println(f"$names%s is $height%2.2f meters tall") // James is 1.90 meters tall
raw-Interpolator
raw
interpolator is similar to the s interpolator except that it performs no escaping of literals within the string. Here’s an example processed string, The raw interpolator is useful when you want to avoid having expressions like\n
turn into a return character. Example:1 2 3
println(raw"This is a \n newline") val escaped = "This is a \n newline" println(raw"$escaped")
for more Information about String Interpolators and their advanced usage visit this Scala-Docs link
- s-interpolators Prepending
Thanks A lot For Visiting My Blog And Reading My Article See You In Next Article