Create a Scala script file in Eclipse

I play with Scala. I only need a set of function definitions, but in Eclipse I can only create .scala files for which the def function must be inside an object or class.

But I see a Scala script online, here , that does not use an object to wrap all functions.

Of course, it’s normal for me to use an object to transfer all my functions, but I'm just wondering if this is required. Thanks!

+7
source share
3 answers

But I see here a Scala script online that does not use an object to wrap all functions.

Please note that in this case functions cannot be called from other files (they end in object with the name generated by the compiler at startup). If you “only need a set of function definitions”, this is probably not what you want :) AFAIK, the Scala IDE does not support script files at the moment, but you can register a function request here .

+2
source

Yes, in Eclipse you need to wrap everything in an object or class.

You can edit Scala scripts in Eclipse while you complete the code in the object and avoid Shebang . Just run the script with scala -i scriptName.scala -e "Main.main(args)" (if you have the "bin" folder in the Scala distribution on path ).

foo.scala:

 object Main extends App { println ("foo") } 

To run it:

 scala -i foo.scala -e "Main.main(args)" 
+2
source

As far as I know, it is impossible to write functions or variables completely out of scope. You can write them outside the class / object definition. You just need to wrap them in an object. What happens mostly is that instead of binding a function / variable to a given class or object, you bind it to a package. Example:

 package test package object inside { def hello = println("Hello from outer space!") class Foo { hello // call the function from the package } } 

Now that you create Foo, you should type "Hello from Space!".

Not knowing completely what I was talking about, I could assume that the version of the script you mentioned above works because the script runs in some kind of environment. So imagine that some class loads a script, and then transfers it to an object and runs it. This would mean a situation similar to the one above: the functions are still “owned” somewhere.

+1
source

All Articles