Home > Article > Backend Development > [Scala Tour] 3-Unified Type - TOUR OF SCALA SiFou
In Scala, all values have a type, including numbers and functions. The following figure demonstrates a subset of the type hierarchy.
Any
Type is the parent type of all types, also known as the top level type. It defines some common methods such as equals
, hashCode
and toString
. Any
has two direct subclasses: AnyVal
and AnyRef
.
AnyVal
represents the value type. There are 9 predefined value types, which are not nullable: Double
, Float
, Long
, Int
, Short
, Byte
, Char
, Unit
, and Boolean
. Unit
is a value type without any meaning. Unit
Only one instance can be declared like this: ()
. All functions must return some value, so Unit
is a useful return type.
AnyRef
represents a reference type. All non-value types are defined as reference types. Every user-defined type in Scala is a subtype of AnyRef
. If Scala is used within a Java runtime environment, then AnyRef
corresponds to Java.lang.object
.
Here is an example that demonstrates that strings, integers, characters, booleans, and functions are objects like other objects:
val list: List[Any] = List( "a string", 732, // an integer 'c', // a character true, // a boolean value () => "an anonymous function returning a string" ) list.foreach(element => println(element))
It defines the type List[ Any]
variable list. The list is initialized with elements of various types, but they are all instances of scala.Any
, so you can add them all to the list.
The following is the output of the program:
a string 732 c true <function>
Value types can be converted in the following ways:
For example:
val x: Long = 987654321 val y: Float = x // 9.8765434E8 (note that some precision is lost in this case) val face: Char = '☺' val number: Int = face // 9786
The conversion is one-way. The last statement below will not compile:
val x: Long = 987654321 val y: Float = x // 9.8765434E8 val z: Long = y // Does not conform
You can also convert a reference type to a subtype. This will be covered in a later article.
Nothing
are subtypes of all types, also known as bottom types. Type Nothing
has no value. Common uses are to signal non-termination, such as throwing an exception, program exit, or infinite loop (i.e., it is an expression that does not evaluate to a value, or a method that does not return a normal value).
Null
is a subtype of all reference types (that is, any subtype of AnyRef
). It has a single value identified by the keyword null
. Null
is primarily used for interoperability with other JVM languages and should almost never be used in Scala code. We'll cover alternatives to null
in a later article.
The above is the detailed content of [Scala Tour] 3-Unified Type - TOUR OF SCALA SiFou. For more information, please follow other related articles on the PHP Chinese website!