最高的父类型为Any,最低类型为Nothing
Any
is the supertype of all types, also called the top type. It defines certain universal methods such as equals
, hashCode
, and toString
. Any
has two direct subclasses: AnyVal
and AnyRef
注意:hashCode,equals,toString方法在Any类型中
AnyVal
represents value types.
There are nine predefined value types and they are non-nullable: Double
, Float
, Long
, Int
, Short
, Byte
, Char
, Unit
, and Boolean
. Unit
is a value type which carries no meaningful information. There is exactly one instance of Unit
which can be declared literally like so: ()
. All functions must return something so sometimes Unit
is a useful return type
值类型是不能为null,Unit代表不携带任何有意义的信息
//test AnyVal is not null-able //compile error //error msg an expression of type Null is ineligible for implicit conversion val xi :Int = null
AnyRef
represents reference types. All non-value types are defined as reference types. Every user-defined type in Scala is a subtype of AnyRef
. If Scala is used in the context of a Java runtime environment, AnyRef
corresponds to java.lang.Object
//AnyRef在Java运行环境中相当于java.lang.Object
类型转换
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
Casting is unidirectional. This will not compile
类型转换未按照图中的方向,不编译.
意思就是scala类型转换一定是安全的.不能由长类型转成短类型(这句话或许有错,因为Long可以转换成Float)
Char不能到Long应该是scala的编译不能识别这种转换,以后在爬这个事的原因
val x: Long = 987654321 val y: Float = x // 9.8765434E8 val z: Long = y // Does not conform
Nothing
is a subtype of all types, also called the bottom type. There is no value that has type Nothing
. A common use is to signal non-termination such as a thrown exception, program exit, or an infinite loop (i.e., it is the type of an expression which does not evaluate to a value, or a method that does not return normally).
Null
is a subtype of all reference types (i.e. any subtype of AnyRef). It has a single value identified by the keyword literal null
. Null
is provided mostly for interoperability with other JVM languages and should almost never be used in Scala code. We’ll cover alternatives to null
later in the tour.
Null在scala中用null代替,为了保证scala和其他Java虚拟机语言的互操作性