Explanation of singleton objects in Scala

后端 未结 4 500
Happy的楠姐
Happy的楠姐 2021-01-31 03:16

I get the coding in that you basically provide an \"object SomeClass\" and a \"class SomeClass\" and the companion class is the class declaration and the object is a singleton.

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 03:23

    Yes, companion singletons provide an equivalent to Java's (and C++'s, c#'s, etc.) static methods.

    (indeed, companion object methods are exposed via "static forwarders" for the sake of Java interop)

    However, singletons go a fair way beyond this.

    • A singleton can inherit methods from other classes/traits, which can't be done with statics.
    • A singleton can be passed as a parameter (perhaps via an inherited interface)
    • A singleton can exist within the scope of a surrounding class or method, just as Java can have inner classes
    • It's also worth noting that a singleton doesn't have to be a companion, it's perfectly valid to define a singleton without also defining a companion class.

    Which helps make Scala a far more object-oriented language that Java (static methods don't belong to an object). Ironic, given that it's largely discussed in terms of its functional credentials.

提交回复
热议问题