Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Scala equivalent of Java's static block?

What is Scala equivalent of Java's static block ?

like image 961
missingfaktor Avatar asked Feb 27 '10 11:02

missingfaktor


People also ask

What is the equivalent of a static class in Scala?

Scala classes cannot have static variables or methods. Instead a Scala class can have what is called a singleton object, or sometime a companion object.

Can Scala have static members?

In Scala, we use class keyword to define instance members and object keyword to define static members. Scala does not have static keyword, but still we can define them by using object keyword. The main design decision about this is that the clear separation between instance and static members.

What is static in Scala?

Scala is more object oriented language than Java so, Scala does not contain any concept of static keyword. Instead of static keyword Scala has singleton object. A Singleton object is an object which defines a single object of a class.

How do I create a static variable in Scala?

There are no static variables in Scala. Fields are variables that belong to an object. The fields are accessible from inside every method in the object. Fields can also be accessible outside the object, depending on what access modifiers the field is declared with.


1 Answers

Code in the constructor (that is, the body) of the companion object is not precisely the same as code in a static initialiser block of a Java class. In the example below, I create an instance of A, but the initialization does not occur.

scala> object Test { class A; object A { println("A.init") }}         defined module Test  scala> new Test.A res3: Test.A = Test$A@3b48a8e6  scala> Test.A A.init res4: Test.A.type = Test$A$@6e453dd5 

To trigger construction of the companion object when the first instance of the class is created, you could access it from the class constructor.

scala> object Test { class A { A }; object A { println("A.init") }} defined module Test  scala> new Test.A                                                   A.init res5: Test.A = Test$A@4e94a28e  scala> new Test.A res6: Test.A = Test$A@30227d4e 

In many circumstances, the difference would not matter. But if you are launching missiles (or other side effects), you might care!

like image 142
retronym Avatar answered Sep 30 '22 22:09

retronym