0

If scala methods belong to classes, how come can one create a method outside of a class?

As in:

def hello(a:String) {println(s"Hello $a")}

What class does this method belong to?

And why is there such a concept (method outside of class) at all? My first impression is that it generates a lot of confusion, since it is redundant (you can already have "normal" functions).

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Michele Piccolini
  • 2,634
  • 16
  • 29

1 Answers1

2

Actually if you put this code to file Smth.scala and try to compile it you'll see that it doesn't

Error:(1, 1) expected class or object definition
def hello(a:String) {println(s"Hello $a")}

I guess you wrote this code in repl. In repl every line is compiled in some object.

In Scala 3 top-level definitions will become possible

https://dotty.epfl.ch/docs/reference/dropped-features/package-objects.html

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • I am writing scala from within zeppelin notebooks. So, a REPL indeed. What is this "some object" in which methods are compiled in the REPL, then? – Michele Piccolini Sep 30 '19 at 10:49
  • 1
    @MichelePiccolini https://docs.scala-lang.org/overviews/repl/overview.html "In interactive mode, the REPL reads expressions at the prompt, **wraps them in an executable template**, and then compiles and executes the result." – Dmytro Mitin Sep 30 '19 at 10:57
  • 2
    @MichelePiccolini: The standard Scala REPL creates a new object for every line. This is the only way in which things that you would like to do in a REPL, such as re-defining a `val` to correct a typo can be sensibly made to work without significantly changing the language just for the sake of the REPL. You will sometimes see those objects in stacktraces if you force an error. – Jörg W Mittag Sep 30 '19 at 13:07