Scala Type Hierarchy and Expressions
November 26, 2019 Leave a comment
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
Recent Comments