Significance of main method

Hi Team,

Let me first present my understanding of how scala complies and run and then in the subsequent comments i would explain the issue.

When whenever we write a code in java with singleton object as mentioned below

1)I have created a new directory scala,inside this directory i have created a file MyScala
and this file contains the below code:
object MyScala{
def main(args: Array[String]){
println (“MyScala”)
}
}
Icomplied the above file using scalac and ran it using scala commands

When iam trying to decompile it using javap:PFB

image

It seems that the main method that i defined in my singleton object in scala gets converted to public static main function in java and thats how JVM is able to execute the code after the scala complier converts the above code into java byte code.

Please correct my understanding if iam wrong.

Lets say i don’t mention this main method and my new code is
object MyScala
{
println(“MyScala”)
}
I compile it and ran it then it fails with the error:

Thus it is clear the due to the absence of main method JVM is not able to execute it.

Now what i fail to understand is if i excute the same code in scala command prompt without using main method it gets successfully executed.PFB the ss:

Shouldn’t i have received an error as i received in the earlier section.

Kindly look into this and clarify my understanding.

In the first case you are creating a scala fine and after compiling it will be converted into executable bytecode and you can run it any number of time. It will upload into memory.
Once run the object will created and main function should be defined.

in second case you are running inside the scala prompt. Your scala object is created at RAM at that instance of time. Once you will come out that object will no longer exists. Here you are directly interacting with scala compiler.

So according to you while interacting directly with scala compiler we don’t need to use the main method and still the code would get successfuly executed due to the reason that you mentioned above.

In scala prompt if you can define an object with class/function (main or others) or just object.
But you need to call the function to see the object defined!

But if it is a normal scala file. if you do not include the main then the object will be defined while compilation! but the executions of the object cannot start without main() function so no result!

I have created the same file that you are creating.


Thanks a lot Sir :slight_smile: