This page discusses the Scala language and its parameters and variables.
Functional programming can be more efficient if we work with non-changable (immutable) values. When we declare objects we therefore distinguish between:
- val - declaring an object whose value does not change (immutable).
- var - declaring an object whose value can change (mutable).
Whenever possible it is best to use 'val' which may give the compiler more possibilities for optimisation.
The form of the declaration is:
var name: type=value;
where:
- val = indicates a value declaration, if we want a varable declaration we would use var.
- name = name of the object instance.
- type = type of object
- value = the value
This compares with java as follows:
Java | Scala | |
Variable declaration | int i=0; | var i: int=0; |
Constant declaration | final int i=0; | val i: int=0; |
Some differences between value (val) and variable (var)
val | var | |
value | The value must be constant values | The value can include symbolic types |
value evaluated | when declared | when needed |
Co-Data Types
algebraic data type:
datatype BinTree = Empty | Node(Int, BinTree, BinTree)
we could use case classes:
abstact class BinTree case class EmptyTree() extends BinTree case class Node(elem: Int, left : BinTree , right : BinTree) extends Bintree |
or Either
Either[Int, String]