Scala-伴生对象于孤立对象
Scala虽然是基于JVM构建的,但与Java还是有很多区别,其实一个重要的区别是Scala比Java更面向对象(纯面向对象),最明显的用例是scala中所有的操作符都是方法(操作符面向的使用者是对象)。
伴生对象/孤立对象也是scala作为纯面向对象语言的一种体现。
孤立对象
先看一个例子
object Test{
var a = "helloworld"
def helloworld(): Unit = {
println("helloworld")
}
}
使用时,它给人的感觉类似下面的代码
public class Test {
public static String a = "helloworld";
public static void helloworld() {
System.out.println("helloworld");
}
}
所以,我们可以向下面的方式访问a
字段或helloworld()
方法
Test.a
Test.helloworld()
这会给人以上的错误,但实际情况并非如此,此处的Test实际上是一个对象(全局单例),看下面的例子
object Test{
var a = "helloworld"
def helloworld(): Unit = {
println("helloworld")
}
def main(args: Array[String]) {
println(Test)
}
}