A Collection in programming is a simple object used to collect data. It groups together elements into a single entity (object). You can do the operation is to add, delete, update data using collections. The Collection in Scala can be mutable as well as immutable.
A Mutable collection is a collection whose elements can be
updated and elements are added or removed from it. It allows all these
operations.
An Immutable collection does not allow the user to do the update operation or add and remove operation on it. There is an option to do this, but on every operation, a new collection is created with updated value and the old one is discarded.
Scala collections have a rich hierarchy. The traversable trait is at the root of Scala hierarchy, all classes inherit some traits that are required for the general functioning of the collections.
LIST, Tuple, Map, Set and Option are 5 kinds of Immutable collections used in Scala.
1)
LIST: collection of sequence of single data
type. The list is a linear array-like
collection. It stores a similar type of elements and uses a linked list type
storage method.
List is an immutable collection that extends linearSeq trait.
numList is an integer collection of
data.
Similarly, numStr is character
collection of data.
Now, to check the First and Last
Values inside the List, type below commands:
To keep away from duplicates:
2) Tuple: combination or grouping of different
data types. It can contain a fixed number of
elements of different types i.e. it can hold an integer and string together.
To access the First Element in Tuple,
type t._1
Likewise, Tuple can be created with
maximum of 22 elements.
Example of Nested elements in Tuple:
3) Map: collection of Key Value Pairs. To retrieve the value the key is used.
4) Set: collection that contains elements of the same data type, it does not contain any duplicate elements. Set can mutable as well as immutable in Scala.
5) Option: either gives 0 or 1 à “Some” or “None” output.
An Expression in a Scala:
Unit
datatype(): If particular code gives Unit datatype, we
call it as ‘Statement’.
Expression: If
particular piece of code returns a value, then called ‘expression’. If last
line is not assignment, then that comes under an expression. All Expressions
are Immutables.
scala> amt
res0: Int = 30
Println: this is Unit datatype and mutability function.
IF statement: This is
String datatype. Parent datatype is ‘Any’ ref.
If not divisible by 2;
For Integer, Any Val is parent datatype.
The collection includes all those data structures that are
used to store multiple elements or collections of elements like Array, List,
Set, Vector, etc.
No comments:
Post a Comment