In this article we shall discuss how the Unified Type System works in Scala. A Unified Type System essentially means that there is one Super-Type from which other Sub-Types inherit. In Scala the Super-Type is the class Any. Therefore class Any is referred to as the root. From Any, two subclasses are derived.
In the above diagram,
Scala
OUTPUT:
- AnyVal: All the value types extend to the AnyVal class. There are nine predefined value types and they are non-null able: Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean.
- AnyRef: All the reference types extend to the AnyRef class. User-defined classes define reference types by default; i.e. they always (indirectly) subclass scala.AnyRef. scala.AnyRef in java programming corresponds to java.lang.Object.
In the above diagram,
- Arrows represent inheritance.
- Double lines represent the hierarchy and implicit type conversion.
- A greater amount of Type Safety as opposed to other type systems.
- Interoperability and integration of objects created in other languages is easier.
- All variables have access to certain universal methods such as equals, hashCode, toString. This is because all the variables are instances of classes which are inherited from the Root class Any, where the universal methods are defined.
// Scala Program to print common elements
// from 2 lists
object Geek
{
def main(args:Array[String])
{
// Creating a list with a fixed data type
val GfG : List[String] = List("Geeks","for","Geeks")
// Creating a List which can take
// variable data type input by Using Any
val myList : List[Any] = List(
"Geeks",
"for",
"Geeks",
1000,
525)
myList.foreach( value => {
//.contains() is an universally declared function
if (GfG.contains(value)){
println(value)
}
})
}
}
Geeks for GeeksIn the above example we see that we were able to create a list containing values of different data types by specifying the type Any. Since Any is the root class, this expression is legal. Further, we have used a method .contains() to see if the List GfG contains a particular element. The .contains() method can be used on Lists, Sets and certain other collections since it is an universal function which is present in Any class. This is possible only due to the Unified Type System which thus makes scala more robust and functional as a language to deal with Big Data Analytics.