Write Java Program to grade Scala Homeworks

Scala generates class files. Scala class files can be run with java, only requiring the scala-library.jar to be on the class path. The entry point on Scala programs appears to Java as a static main method on a class, just like in Java. The difference is that, in a Scala program, that main method is a method declared on an object. For example:

Java:

public class Test {
    public static void main(String[] args) {
    }
}

Scala:

object Test {
    def main(args: Array[String]) { 
    // or:
    // def main(args: Array[String]): Unit = { 
    }
}

The idea of testing by giving unit tests is interesting, but it will probably force non-idiomatic Scala code. And, in some rare cases, might even prevent the solution to be written entirely in Scala.

So I think it is better to just specify command line arguments, input (maybe stdin), and output (stdout). You can easily run it with either scala Test parms, or java -cp /path/to/scala-library.jar Test parms.

Testing input on individual functions might be a lot harder, though, as they may require Scala classes as input, and some of them can be a bit tough to initialize from Java. If you go that route, you’ll probably have to ask many more questions to address specific needs.

One alternative, perhaps, is using Scala expressions from the command line. For example, say you have this code:

object Sum {
  def apply(xs: Seq[Int]) = xs reduceLeft (_ + _)
}

It could be tested as easily as this:

dcs@ayanami:~/tmp$ scalac Sum.scala
dcs@ayanami:~/tmp$ scala -cp . -e 'println(Sum.apply(Seq(1, 2, 3)))'
6

To do the same from Java, you’d write code like this:

import scala.collection.Seq$;

public class JavaTest {
    static public void main(String[] args) {
        System.out.println(Sum.apply(Seq$.MODULE$.apply(scala.Predef.wrapIntArray(new int[] {1, 2, 3}))));
    }
}

Leave a Comment