7

I am playing with Scala. What I need is just a brunch of function definitions, but in Eclipse I can only create .scala files for which a function def must be inside an object or class.

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

It is of course ok for me to use an object to wrap all my functions, but I am just wondering whether it is required. Thanks!

1
  • 3
    You can edit scripts without wrapping in an object in IntelliJ Commented Oct 30, 2011 at 14:48

3 Answers 3

2

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

Note that in this case, the functions can't be called from other files (they are wrapped in an object with compiler-generated name when run). If you "need just a brunch of function definitions", this is likely not what you want :) AFAIK, Scala IDE doesn't support script files at the moment, but you could log a feature request here.

Sign up to request clarification or add additional context in comments.

Comments

2

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

You can edit Scala scripts in Eclipse as long as you wrap the code in an object and avoid the Shebang. Just run the script with scala -i scriptName.scala -e "Main.main(args)" (providing you have the "bin" folder of scala distribution on your path).

foo.scala:

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

To run it:

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

Comments

1

To my knowledge it isn't possible to write functions or variables completely outside of scope. That said it is possible to write them outside of class/object definitions. You just have to wrap them in a package object. What's happening is basically that instead of tying the function/variable to a given class or object, you tie 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, when you construct Foo, you should get printed "Hello from outer space!".

Without knowing completely what I'm talking about, I could imagine that the script version you mentioned above works, because the script is being run in some kind of an environment. So imagine some class loading the script, then wrapping it into an object and the running it. That would imply a situation somewhat like the one above: the functions still "belong" to somewhere.

1 Comment

Scala supports script-style, without any need of classes, objects or package objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.