(2) Scala Entry
About
:octocat: GitHub: All of the example code: repo (link)
:page_facing_up: blog link: https://purrgramming.life/cs/programming/fp/ :star:
Getting Started
Functions and Methods
Functions
A function
- is a collection of statements that perform a certain task.
- is used to put some common and repetitive tasks into a single function, so we can call the function instead of writing the same code again and again for different inputs.
- Scala is assumed as a functional programming language, so these play an important role. It makes it easier to debug and modify the code. Scala functions are first-class values.
Functions vs Methods
Function – an object which can be stored in a variable.
Method – always belongs to a class with a name signature bytecode.
etc. You can say a method is a function that is a member of some object.
Conditionals
To express choosing between two alternatives, Scala has a conditional expression if-then-else.
Example:
def absoluteValue(x: Int) = if (x >= 0) x else -x
absoluteValue(1) // val res0: Int = 1
absoluteValue(-2) // val res1: Int = 2
where x >= 0
is a predicate, of type Boolean
.
Boolean Composition
Boolean expressions b can be composed of
true false // Constants
!b // Negation
b && b // Conjunction
b || b // Disjunction
Example: The usual operations:
e <= e
e == e
e != e
Clean Code
!true --> false
!false --> true
true && e --> e
false && e --> false
true || e --> true
false || e --> e
Note that && and || do not always need their right operand to be evaluated.
Semicolons
If there are more than one statement on a line, they need to be separated by semicolons:
val y = x + 1; y * y
At the end of lines, semicolons are usually (and should be) left out.
You could write
val x = 1;
but it would not be very conversational in Scala
Blocks and Lexical Scope
Blocks
A block is delimited by braces { ... }
.
A block
- contains a sequence of definitions or expressions.
- may appear everywhere an expression can.
Example block
{ val x = 3
x * x // the return of the block
}
Result
val x: Int = 3
val res0: Int = 9
Block return
-
the last element of a block is an expression that defines its value
- (The
x * x
in this block ).- This return expression can be preceded by auxiliary definitions.
Braces
- (The
From Scala 3, braces are optional (i.e. implied) around a correctly indented expression that appears after =, then, else, …
Scala 2
val y = 3
if (y != 1) {
println ("y is 1")
}
Scala 3
val y = 3
if y != 1 {
println ("y is not 1")
}
Visibility – 3 Rules
Rule 1/3 – The definitions inside a block are only visible from within the block
def plusOne(z: Int) = {
z + 1
}
z // Error: Not found: z
Rule 2/3 – The definitions inside a block shadow definitions of the same names outside the block.
val x = 0
def plusFour(y: Int) = {
val x = 3
y + x + 1 // x = 3
}
plusFour(3) // val res1: Int = 7
Rule 3/3 Lexical Scoping: Definitions of outer blocks are visible inside a block unless they are shadowed.
val a = 2
def plusThree(b: Int) = {
a + b + 1 // a = 3
}
plusThree(1) // val res1: Int = 4
Syntax Summary
We have seen language elements to express types, expressions, parameters and
definitions.
Extended Backus-Naur form
In computer science, Extended Backus–Naur Form (EBNF) is a family of metasyntax notations, any of which can be used to express context-free grammar.
| denotes an alternative,
[...] an option (0 or 1),
{...} a repetition (0 or more)
Types
A type can be:
- A numeric type: Int, Double (and Byte, Short, Char, Long, Float),
- The Boolean type with the values true and false,
- The String type,
- A function type, like Int => Int, (Int, Int) => Int.
Expressions
An expression can be:
- An identifier such as x, isGoodEnough,
- A literal, like 0, 1.0, ”abc”,
- A function application, like sqrt(x),
- An operator application, like -x, y + x,
- A selection, like math.abs,
- A conditional expression, like if x < 0 then -x else x,
- A block, like { val x = abs(y) ; x * 2 }
- An anonymous function, like x => x + 1.
Definitions
A definition can be:
- A function definition, like def square(x: Int) = x * x
- A value definition, like val y = square(2)
Parameter
A parameter can be:
- A call-by-value parameter, like (x: Int),
- A call-by-name parameter, like (y: => Double).
Scala and Java
Similarities
Similarities between Scala and Java
1) Both are JVM based language
2) You can call Scala from Java and Java from Scala
3) Major Java programming IDE like Eclipse, Netbeans and IntelliJ supports Scala.
4) Both are Object Oriented. Scala goes one step further
Scala vs Java
Differences between Scala and Java
Parameters of Comparison | Scala | Java |
---|---|---|
Design | It is an objective-oriented language | It is a mixture of objective and functional programming |
Backward compatibility | Supports backward compatibility (interoperability with an older legacy system) | Don’t modify it |
Laziness | Operators are not managed using method calls (lazy) | All operators are managed through method calls |
Conciseness | Shorter code – clever use of type inference, treating everything as an object, function passing, and several other features. | Longer : ) |
Objective oriented | More object-oriented | Less object-oriented |
Functional | More function (and encourage immutable style ) | Less functional |
Functions are … | first-class elements | objects |
Operator overloading | √ | X |