Scala Type Hierarchy and Expressions

Type Hierarchy

Expressions
In imperative languages like Java/Python we execute instructions. For example IF conditional statement is an Instruction. Whereas in Scala, we execute expressions.

IF conditional statements are expressions that can return some value.

val aConditionValue = if (aCondition) 5 else 3
Code Blocks are also expressions that can return something
val someOtherValue = {
        if (someValue) 233 else 422
        42
    }

Code Blocks are commonly used expression blocks which can contain one or more expressions and the return type is the return value from the last expression.

val aCodeBlock = {
   if(true) 54
   56
}

Throwing exception from a method returns Nothing “()”
Any methods (println) that have side effects returns Unit
so on..

In functional programming languages writing loops are not encouraged. Whenever there is a need to write a loop we should go for recursion. Optimized way to write recursion is to use TAIL RECURSION technique.
To ensure we are using tail recursion we can use “@tailrec” before the function definition

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: