Scala class of out-of-class method

322 Views Asked by At

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).

1

There are 1 best solutions below

3
Dmytro Mitin On

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