Scala如何使用单例对象和伴随对象?

本文概述


Scala单例对象

单例对象是通过使用object关键字而不是通过类声明的对象。调用单例对象内部声明的方法不需要对象。

在scala中, 没有静态概念。因此, scala创建了一个单例对象, 以提供程序执行的入口点。

如果不创建单例对象, 则代码将成功编译, 但不会产生任何输出。在Singleton Object中声明的方法可以全局访问。单例对象可以扩展类和特征。

Scala单例对象示例

object Singleton{
    def main(args:Array[String]){
        SingletonObject.hello()         // No need to create object.
    }
}


object SingletonObject{
    def hello(){
        println("Hello, This is Singleton Object")
    }
}

输出

Hello, This is Singleton Object

Scala伴随对象

在Scala中, 当你拥有与单例对象同名的类时, 该类称为伴随类, 而单例对象称为伴随对象。

伴随类及其伴随对象都必须在同一源文件中定义。

Scala伴随对象示例

class ComapanionClass{
    def hello(){
        println("Hello, this is Companion Class.")
    }
}
object CompanoinObject{
    def main(args:Array[String]){
        new ComapanionClass().hello()
        println("And this is Companion Object.")
    }
}

输出

Hello, this is Companion Class.
And this is Companion Object.
微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_47822.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?