scalascala-scriptscala-cli

Import / include / using objects from another source file into a Scala script file


I have a MyScript.scala file:

//> using scala "3"

object MyUtils {
  def sayHello() = println("Hello")
}

@main
def main(): Unit =
  MyUtils.sayHello();

I successfully run it like this:

> scala MyScript.scala

Compiling project (Scala 3.6.4, JVM (17))
Compiled project (Scala 3.6.4, JVM (17))
Hello

Question: What do I need to do to move my MyUtils object into another source file (e.g., MyUtils.scala or MyUtils.sc) and still call the sayHello method from within MyScript.scala?


Solution

  • With the Scala CLI, you can use the using file directive.

    For instance, in the main file:

    //> using scala "3"
    //> using file Utils.scala
    
    @main
    def main(): Unit = {
      MyUtils.sayHello()
    }
    

    And the imported file Utils.scala:

    object MyUtils {  
      def sayHello() = println("Hello")
    }
    

    Reference : https://scala-cli.virtuslab.org/docs/guides/scripting/scripts#define-source-files-in-using-directives