AnyVal

AnyVal represents value classes. All value classes are predefined; they correspond to the primitive types of Java-like languages.

  1. There are nine predefined value types and they are non-null able: Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean.
  2. Scala has both numeric (e.g., Int and Double) and non-numeric types (e.g., String) that can be used to define values and variables.
  3. Boolean variables can only be true or false. Char literals are written with single-quotes.
  4. These are not nullable except Unit and all value classes are an abstract final type.

Example:

Scala




// Scala program of Scala Type hierarchy
// Using AnyVal.
 
// Creating Object
object Geeks
{
 
    // Main method
    def main(args: Array[String])
    {
        val list: List[AnyVal] = List(
            333, true, false
            )
 
        list.foreach(element => println(element))
    }
}


Output

333
true
false


Scala Type Hierarchy

There are no primitive types in Scala(unlike Java). All data types in Scala are objects that have methods to operate on their data. All of Scala’s types exist as part of a type hierarchy. Every class that we define in Scala will also belong to this hierarchy automatically.

Any

Any is the superclass of all classes, also called the top class. It defines certain universal methods such as equals, hashCode, and toString. Any has two direct subclasses:

  1. AnyVal
  2. AnyRef

Example:

Scala




// Scala program of Scala Type hierarchy
 
// Creating object
object Geeks
{
 
    // Main method
    def main(args: Array[String])
    {
        val list: List[Any] = List(
                false,
                66677,
                732,
                'a',
                "abs"
                    )
 
        list.foreach(element => println(element))
    }
}


Output

false
66677
732
a
abs


Similar Reads

AnyVal

...

Exception

AnyVal represents value classes. All value classes are predefined; they correspond to the primitive types of Java-like languages....

AnyRef

...

Nothing and Null

Scala’s value types are much like Java’s primitive types except the Unit class....