'Error when running scala script from terminal; however :load works fine inside interpreter

I am trying to learn Scala, or at least the basics for now. I went to the scala website to download it from there. I followed the steps and download Coursier and called cs setup and then cs install scala:3.1.1 and cs install scalac:3.1.1.

I started writing simple scripts without classes, like how you'd do in the interpreter. So I opened a text file and wrote print('x') and saved it to filename.scala, then I went to terminal and tried scala filename.scala; however, that gave me the error ("Illegal start of toplevel definition"). I changed the code inside the .scala file to a simple var x : Int 4, and I get a different error ("Error: No main methods detected in script Desktop/filename.scala").

When I open the scala terminal and use the :load option, everything works fine. After looking around SO for a good half an hour, none of the mentioned answers helped. I understand that scala is looking for a full program with objects and methods like java. But from what I read, it should be able to run scripts like the one I wrote by guessing its type. What's the problem? Is this a problem with scala 3 or my terminal? or am I doing something wrong?

Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source