Doing something like “importing” Python into Scala

Is it possible to use Scala importwithout specifying the main function in the object and without using a keyword packagein the source file with the code that you want to import?

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

from Lib import *

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

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

+5
source share
4 answers

Writing Python to Scala is unlikely to give satisfactory results. Objects are not "redundant" - this is your program, which is not written in an object-oriented way.

First, methods must be inside objects. You can place them inside package object, and then they will be visible to everyone inside the package with the same name.

Secondly, if we consider only objects and classes, then all objects without packages and classes whose class files are present on the class path or whose Scala files are compiled together will be visible to each other.

+1
source

This is the minimum as I could get:

[$]> 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
+1
source

, Scala REPL. - .

0

/ , . , , , .. , , .

, , . , ( DelayedInit) , .

script, - , (REPL) .

0

All Articles