Jwan622
Jwan622

Reputation: 11639

How do I get args passed to this scala object?

I'm trying to figure out how to pass args to this scala object:

I have this class written in this sbt project path: allaboutscala/src/main/scala/gzip_practice/gzipwriter

package gzip_practice

import java.io._
import java.util.zip._

/** Gzcat
    */
object gzcat extends App {
    private val buf = new Array[Byte](1024)

    try {
        for (path <- args) {
            try {
                var in = new GZIPInputStream(new FileInputStream(path))
                var n = in.read(buf)
                while (n >= 0) {
                    System.out.write(buf, 0, n)
                    n = in.read(buf)
                }
            }
            catch {
                case _:FileNotFoundException =>
                    System.err.printf("File Not Found: %s", path)
                case _:SecurityException =>
                    System.err.printf("Permission Denied: %s", path)
            }
        }
    }
    finally {
        System.out.flush
    }
}

This is an sbt project called allaboutscala. I am trying to run it with: scala src/main/scala/gzip_practice/gzipwriter.scala "hi" but the command just hangs and I don't know why.

How am I supposed to run this object constructor with args?

Upvotes: 0

Views: 423

Answers (3)

som-snytt
som-snytt

Reputation: 39577

You can use the scala command as a script runner.

Normally, it will wrap your "script" code in a main method.

But if you have an object with a main method, like your App, it will use that for the entry point.

However, it doesn't like package statements in the script.

If you comment out your package statement, you can compile and run with:

scala -nc somefile.scala myarg.gz

-nc means "no compile daemon"; otherwise, it will start a second process to compile scripts, so that subsequent compiles go faster; but it is a brittle workflow and I don't recommend it. I confirmed that your code works.

Usually, folks use sbt or an IDE to compile and package in a jar to run with scala myapp.jar.

Upvotes: 1

Pietrotull
Pietrotull

Reputation: 497

Are you trying to run it with repl? I would suggest running it with sbt, then you can run sbt projects from project root directory with command line parameter as follows:

sbt "run file1.txt file2.txt"

The quotes are required. If you leave sbt shell open, then it running it will be much faster. Open shell in project root with

sbt

In the sbt shell:

run file1.txt file2.txt

Within the sbt shell, no quotes.

Upvotes: 0

Bob Dalgleish
Bob Dalgleish

Reputation: 8227

An object is a static instance of a class. You could construct it using:

object gzcat(args: String*) extends App {
  ...
}

args is bound as a val within the object gzcat.

Upvotes: 0

Related Questions