What is the equivalent of static block Java in scala language



Please can any one let me know what is the equivalent of static block in java in scala.
class Configurator{
set of statements // which need to be executed while class loading (before main method execution starts)


will create jar and import it into the another application and access the static methods if any in the companion object



You normally put that code into companion object of your class:

object Configurator {
  // initialization code here
class Configurator {


The equivalent of Java static blocks in Scala is simply code in the companion object that is not already part of a field or method definition.

Fields in a Scala companion object correspond to static fields in Java, methods in the companion to static methods, and all other code to static blocks.


Thank you :smile:., I will approach the way you suggested…


Please can you provide in understanding of loading Static block code while loading the class.
have code as below
Created a package package1.Configurator inside this package Configurator object.
and added the code mentioned below and Created the jar for the same.
and imported into the Main class
the code is mentioned in the Object Configurator need to be executed while loading the class[Before main method flow execution]

object Configurator {
// initialization code here

var fileNameArray: Array[String] = System.getProperty(“spark.app.config.filenames”).split(",")

val fileNameSeq = fileNameArray.map(e => e + “.conf”).toSeq
// this creates config object
val mergedConfig = fileNameSeq.foldLeft(ConfigFactory.empty()) { (acc, configName) =>
val config = ConfigFactory.load(configName)

def getString(key:String):String = {


class Configurator { }
Below is the another application in which imported above package, and expecting the above code executed before main method [ just like static block does in Java] ----------------------------------------------------------------
import package1.Configurator
object Main {

def main(args: Array[String]) {
//execution flow starts here…
// should be able to get the value of key after calling the getString method which is there in Configurator Object




Can you please provide example…

static fields
static method
static block (which should be executed when the class loads at run time - just like static block works in Java)



Keep in mind that class X and object X are defined by different JVM classes (namely X and X$). See following code:

object Main extends App {
	println("before new class instance")
	new X()
	println("before forcing object initialization")
class X {
	println("initializing class")
object X {
	println("initializing object")


before new class instance
initializing class
before forcing object initialization
initializing object