Scala 单例和companion对象
单例对象
Scala是一种比Java更加面向对象的语言,所以Scala 不 包含任何 静态 关键字的概念。Scala有 单例对象 ,而不是静态关键字。单例对象是一个定义了一个类的单一对象的对象。一个单例对象为你的程序执行提供了一个入口点。如果你没有在你的程序中创建一个单例对象,那么你的代码会被成功编译,但不会有输出。所以你需要一个单例对象来获得你的程序的输出。一个单例对象是通过使用 object 关键字创建的。
语法:
object Name{
// code...
}
关于单例对象的重要观点
- 单例对象中的方法是全局可访问的。
- 你不允许创建单例对象的实例。
- 你不允许在单例对象的主构造函数中传递参数。
- 在Scala中,单例对象可以扩展类和特质。
- 在Scala中,单例对象中总是有一个主方法。
- 单例对象中的方法是用对象的名字来访问的(就像在Java中调用静态方法一样),所以不需要创建一个对象来访问这个方法。
例1:
// A simple Scala program to illustrate
// the concept of singleton object
class AreaOfRectangle
{
// Variables
var length = 20;
var height = 40;
// Method which gives the area of the rectangle
def area()
{
var ar = length * height;
println("Height of the rectangle is:" + height);
println("Length of the rectangle is:" + length);
println("Area of the rectangle is :" + ar);
}
}
// singleton object
object Main
{
def main(args: Array[String])
{
// Creating object of AreaOfRectangle class
var obj = new AreaOfRectangle();
obj.area();
}
}
输出:
Height of the rectangle is:40
Length of the rectangle is:20
Area of the rectangle is :800
例2:
// A Scala program to illustrate
// how to call method inside singleton object
// Singleton object with named
// as Exampleofsingleton
object Exampleofsingleton
{
// Variables of singleton object
var str1 = "Welcome ! GeeksforGeeks";
var str2 = "This is Scala language tutorial";
// Method of singleton object
def display()
{
println(str1);
println(str2);
}
}
// Singleton object with named as Main
object Main
{
def main(args: Array[String])
{
// Calling method of singleton object
Exampleofsingleton.display();
}
}
输出:
Welcome ! GeeksforGeeks
This is Scala language tutorial
解释: 在上面的例子中,我们有两个单例对象,即Animateofsingleton和Main。Exampleofsingleton对象包含一个名为display()的方法,现在我们在Main对象中调用这个方法。使用这个语句 Exampleofsingleton.display(); 我们调用Exampleofsingleton对象中的display()方法并打印输出。
Companion对象
Companion对象 被称为一个名字与类的名字相同的对象。或者换句话说,当一个对象和一个类有 相同的名字 时,那么这个对象就被称为companion对象,而这个类则被称为companion类。一个companion对象被定义在定义类的同一个源文件中。伙伴对象被允许访问类的私有方法和私有字段。
例子:
// A Scala program to illustrate
// the concept of the Companion object
// Companion class
class ExampleofCompanion
{
// Variables of Companion class
var str1 = "GeeksforGeeks";
var str2 = "Tutorial of Companion object";
// Method of Companion class
def show()
{
println(str1);
println(str2);
}
}
// Companion object
object ExampleofCompanion
{
def main(args: Array[String])
{
var obj = new ExampleofCompanion();
obj.show();
}
}
输出:
GeeksforGeeks
Tutorial of Companion object
极客教程