emchristiansen
emchristiansen

Reputation: 3602

Doing something like Python's "import" in Scala

Is it possible to use Scala's import without specifying a main function in an object, and without using the package keyword in the source file with the code you wish to import?

Some explanation: In Python, I can define some functions in some file "Lib.py", write

from Lib import *

in some other file "Run.py" in the same directory, use the functions from Lib in Run, and then run Run with the command python Run.py. This workflow is ideal for small scripts that I might write in an hour.

In Scala, it appears that if I want to include functions from another file, I need to start wrapping things in superfluous objects. I would rather not do this.

Upvotes: 5

Views: 1622

Answers (4)

reggert
reggert

Reputation: 742

Objects/classes don't have to be in packages, though it's highly recommended. That said, you can also treat singleton objects like packages, i.e., as namespaces for standalone functions, and import their contents as if they were packages.

If you define your application as an object that extends App, then you don't have to define a main method. Just write your code in the body of the object, and the App trait (which extends thespecial DelayedInit trait) will provide a main method that will execute your code.

If just want to write a script, you can forgo the object altogether and just write code without any container, then pass your source file to the interpreter (REPL) in non-interactive mode.

Upvotes: 0

Xiong Chiamiov
Xiong Chiamiov

Reputation: 13694

This is as minimal as I could get it:

[$]> cat foo.scala
object Foo {
   def foo(): Boolean = {
      return true
   }
}

// vim: set ts=4 sw=4 et:
[$]> cat bar.scala
object Bar extends App {
    import Foo._

    println(foo)
}

// vim: set ts=4 sw=4 et:
[$]> fsc foo.scala bar.scala
[$]> export CLASSPATH=.:$CLASSPATH # Or else it can't find Bar.
[$]> scala Bar
true

Upvotes: 1

Madoc
Madoc

Reputation: 5919

When you just write simple scripts, use Scala's REPL. There, you can define functions and call them without having any enclosing object or package, and without a main method.

Upvotes: 0

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297165

Writing Python in Scala is unlikely to yield satisfactory results. Objects are not "superfluous" -- it's your program that is not written in an object oriented way.

First, methods must be inside objects. You can place them inside a package object, and they'll then be visible to anything else that is inside the package of the same name.

Second, if one considers solely objects and classes, then all package-less objects and classes whose class files are present in the classpath, or whose scala files are compiled together, will be visible to each other.

Upvotes: 1

Related Questions