Scala Type Hierarchy

Scala doesn’t have any primitive types. All datatypes in Scala are objects.

 
scala type hierarchy
 
Scala has both numeric (e.g., Int and Double) and nonnumeric types (e.g., String) that can be used to define values and variables.
 

Any

 
Class Any is the root of the Scala class hierarchy and is an abstract class.

Every class in a Scala execution environment inherits directly or indirectly from this class.

 

AnyVal

 
AnyVal extends Any type.

The types that extend AnyVal are known as value types.

Numeric types, Boolean, Char, Unit extend AnyVal.

 

AnyRef

 
AnyRef extends Any type.

The types that extend AnyRef are known as reference types

All reference types(Scala classes and User defined classes) extend AnyRef.

 

Numeric types

 
The numeric data types in Scala constitute Float and Double types along with Integral data types such as Byte, Short, Int, Long, and Char.
 
scala numeric types
 
Scala supports the ability to automatically convert numbers from one type to another in the order
Byte -> Short -> Int -> Long -> Float -> Double.

However, Scala does not allow automatic conversion in the reverse order.

For example, the following automatic conversion is ok and y is printed as 10.0

   val x:Int = 10;
    val y:Double = x;
    println(y);

However, the reverse will not compile as show below :

   val x:Double = 10;
    val y:Int = x;//compilation error "type mismatch;found=Double;required=Int"
    println(y);

 

Boolean Type

 
Boolean variables can only be true or false.

   val x:Boolean = false;
    val y:Boolean = !x;

 

Char Type

 
Char literals are written with single-quotes.

 val c = 'C';

 

Unit Type

 
The Unit type is used to define a function that doesn’t return data.

It is similiar to the void keyword in Java.

    val y =();
     println(y);

Output :

()
 

Nothing and Null Type

 
Null is a subtype of all reference types.

Nothing is a subtype of every other type to provide a compatible return type for operations that affect a program’s flow. One of the usages of Nothing is that it signals abnormal termination.
 

String Type

 
Scala’s String is built on Java’s String .

It adds additional features such as string interpolation to Java’s String.

   val x:String ="new string";
   println(x);

Output:

new string

 
 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags