Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What are undefined types in Scala?

Khizar Hayat Saani

Scala allows us to define data without explicitly assigning a particular data type. These data variable types are often referred to as undefined types.

In Scala, the undefined type is represented by Nothing.

However, data is never actually empty, as this type contains the undefined constant.

Behavior

We use the undefined constant when we want a given variable to have an empty type.

Undefined matches all types, serving as a sub-type for all types.

Attempting to evaluate undefined types causes our program to abort without returning an answer.

The undefined type as a base for other data types

Code

In Scala, undefined types are denoted with Nothing. Nothing has no value or methods.

It serves the same function of providing greater flexibility to our code. The Nothing keyword is often used to define generic classes or in exception handling.

object Main{
    
    def main(args: Array[String]) = {
        
        try{
            var x = 3 / 0
        }

        catch
        {
            case ex: Exception => printException(ex);
        }
    }

    def printException(e:Exception):Nothing = {
        println("Exception is: %s".format(e.getMessage))
        throw new Exception("My New Exception")
    }
}
Exception handling using Nothing

In the above example, we try dividing a random integer by zero. This generates an exception that is caught by our catch block.

The catch block forwards the Exception to a function. The function then prints the Exception message and throws a new Exception.

This is possible because our return type was Nothing, which has no value.

RELATED TAGS

scala

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring