Any类整个Scala继承的根,在Scala的运行环境中,Scala的所有类都直接或者间接继承了Any,以下是Any类的成员:
![7C(}PT)FFZ
O0O)(QXFJR.png
其实Scala的很多特性,功能,背后都是Java,例如 函数式编程,背后都是Function1,Function2等等
AnyRef是所有引用类型的父类,AnyRef的父类是Any
![%8{8{W]ISSCED0BF2U}AOOD.png](https://img.haomeiwen.com/i2735954/0f8890c9ec89f2b4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
AnyRef下面几个重要的方法:
![WQ96(0VMUPMIMZJ_U}1K{3.png
这几个方法都是线程操作,也就是说所有继承了AnyRef的对象,都对并发操作有支持
AnyVal 是所有值类型的父类,它是描述了在操作系统下不是以对象的方式存在的
}R7FTW(6$X8@G`%2{8YF$$7.png其实就是把基本类型的封装也变成了对象
所以Scala是彻底面向对象语言,这点和Java不一样,Scala在值类型和引用类型的级别之上,做了一个Any,所以Scala一切皆对象
关于Null:
Null
is - together with scala.Nothing - at the bottom of the Scala type hierarchy.
Null是和Nothing一样,是Scala类型体系中最底层的一员
its only instance is the null
reference. Since Null
is not a subtype of value types, null
is not a member of any such type. For instance, it is not possible to assign null
to a variable of type scala.Int.
Scala的继承体系,源头在Any,一分为2,AnyRef和AnyVal,终结于Nothing
Nothing
is a subtype of every other type (including scala.Null); there exist no instances of this type. Although type Nothing
is uninhabited, it is nevertheless useful in several ways. For instance, the Scala library defines a value scala.collection.immutable.Nil of type List[Nothing]
. Because lists are covariant in Scala, this makes scala.collection.immutable.Nil an instance of List[T]
, for any element of type T
.
Another usage for Nothing is the return type for methods which never return normally. One example is method error in scala.sys, which always throws an exception.
为什么Scala和Java都不希望继承多个抽象类呢?
是因为会产生二义性:
A和B继承D,而C继承A和B,A和B当中都有共同的方法,那C在调用的时候,应该调用谁呢?
看一个函数式编程的例子:
```
object HelloHirachyAndTrait {
** def main(args:Array[String]){**
** val succ=(x:Int) => x+1**
** val func1=new Function1Int,Int{**
** def apply(x:Int):Int=x+1**
** }**
** assert(succ(0)==func1(0))**
** }**
}
```
假如一个子类需要继承trait,而trait中有var,该var不可以复写!!!
最后,说一下trait的背后是什么?
trait ScalaTrait {
def toCode
}
对ScalaTrait.class进行反编译之后:
B)@MS8(R5CJFI7PGL~M1QHM.pngtrait ScalaTrait {
def toCode{}
}
0DTS2{7)~_QYOJ{9OGGIZIA.png
当trait有具体实现的时候,此时方法会变成静态方法,这个也是我们比较喜欢用trait作为工具类的一个很重要的原因
归纳总结:1.关于Any
2.关于AnyRef
3.关于AnyVal
4.关于Null和Nothing
5.函数式变成的背后
6.Trait的背后
网友评论