Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the underlying types of Scala

Shulou Source: shulou.com Published: 2022-06-02 07:18:38 09月26日 Update

This article mainly talks about "what are the underlying types of Scala". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the underlying types of Scala.

At the bottom of the type hierarchy are two classes scala.Null and Scala.Nothing. They are special types that deal with the "boundary case" of some Scala object-oriented type systems in a unified way.

The class Null is a reference to the null type; it is a subclass of each reference class (that is, every class that inherits from AnyRef). Null is not compatible with value types. You cannot, for example, assign a null value to an integer variable:

Scala > val I: Int = null

< console>

: 4errorRanger typemismatch; found:Null (null) required:Int

The type Nothing is on the * side of the class level of Scala; it is a subtype of any other type. However, there is no value of this type at all. What's the point of having a type with no value? One of the uses of Nothing is that it marks an abnormal termination. For example, the Predef object in Scala's standard library has an error method, which is defined as follows:

Def error (message:String): Nothing = throw new RuntimeException (message)

The return type of error is Nothing, which tells the user that the method does not return normally (instead, an exception is thrown). Because Nothing is a subclass of any other type, you can use methods like error very flexibly. For example:

Def divide (x:Int, y:Int): Int = if (y! = 0) x / y else error ("can't divide by zero")

The "then" state branch, x / y, is of type Int, while the "otherwise" (else) branch calls error with type Nothing. Because Nothing is a subtype of Int, the type of the entire state statement is Int, as needed.

At this point, I believe you have a deeper understanding of "what are the underlying types of Scala?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Type method underlying content branch subclass object level state learning practical deeper special two interest variable practicality practicality that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Docker Shulou Technology macOS Linux