Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton Object vs Companion Object in Class

Tags:

scala

I have written the following code:

class a {

  object c {
    var a = "STATIC"

    def m() = print("STATIC METHOD")

    var f = () => print("STATIC FUNCTION")
  }

}

object m {
  def main(args: Array[String]) = {
    var o = new a()
    o.c.m()
  }
}
  1. Can I say that the variables, functions and methods that are declared in object c can be static?
  2. If I change name of object c with a then will the object becomes a companion object?
like image 854
USER Avatar asked May 19 '26 06:05

USER


1 Answers

Scala has no true meaning of 'static' that Java does.

The fact that objects have a backing on the JVM that uses static methods / fields is a leaking implementation detail that you only need to deal with if using Java/JVM interop.

Unless you explicitly need that interop, you need to stop thinking of declared objects as 'static' and instead think of them as singletons within their given scope.

An inner object nested under a class, means that there is only ever going to be 1 instance of that object, for each class instance, unlike inner classes which could have multiple instances.

This applies at the top level as well, except that Scala can do additional compatibility with other JVM languages, and mark some of the methods/members as static.

like image 101
Ryan Leach Avatar answered May 22 '26 01:05

Ryan Leach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!