(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

  • Get up and running with Scala on your computer: link
  • Useful links for learning scala: link

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

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

file

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

Topic Scala Java
Programming style Combines object-oriented and functional programming. Class-based language with lambdas, streams and other functional features.
Functions and methods Function values and methods are distinct; methods can be adapted to functions. Methods and functional-interface objects are distinct; lambdas target functional interfaces.
Evaluation Strict evaluation by default; explicit lazy values and by-name parameters. Ordinary arguments are evaluated before invocation; suppliers can represent deferred work.
Operators Many operators are method calls, subject to language typing and rewriting rules. Built-in operators; no general user-defined operator overloading.
Compatibility Java interoperability does not imply binary compatibility across every Scala major version. Compatibility depends on source/API/class-file versions and the target JDK.

Takeaway

Read expressions by their value, scope and evaluation timing. Keep function values distinct from methods and distinguish Java interoperability from version-to-version compatibility.

Leave a Reply

Your email address will not be published. Required fields are marked *