Scala: defining a basic method that java can use

The usual way to define main in Scala (as shown below) can be used to run classes with scala, but not "java" (since the created method is not static). How to write a Scala class / object that can be executed using java?

object HelloWorld { def main(args: Array[String]) { println("Hello, world!") } } 
+6
scala
source share
4 answers

You are wrong. You can run it with "java", and the reason you gave it as impossibility is incorrect. Here, let me show what is inside the "scala".

Unix:

 #!/bin/sh ... exec "${JAVACMD:=java}" $JAVA_OPTS -cp "$TOOL_CLASSPATH" -Dscala.home="$SCALA_HOME" -Denv.classpath="$CLASSPATH" -Denv.emacs="$EMACS" scala.tools.nsc.MainGenericRunner " $@ " 

Window:

 @echo off ... if "%_JAVACMD%"=="" set _JAVACMD=java ... "%_JAVACMD%" %_JAVA_OPTS% %_PROPS% -cp "%_TOOL_CLASSPATH%" scala.tools.nsc.MainGenericRunner %_ARGS% 

However, if you have a class with the same name, then there is an error that may affect you, depending on the version of Scala you are using.

+7
source share

javap will actually show you that your core is static.

 javap HelloWorld Compiled from "HelloWorld.scala" public final class HelloWorld extends java.lang.Object{ public static final void main(java.lang.String[]); public static final int $tag() throws java.rmi.RemoteException; } 

Perhaps you just need Scala banners on your class path?

There is a similar question in Qaru: " Creating a jar file from a Scala file .

I just confirmed that this works with the instructions (related) above.

Just run through:

 java -jar HelloWorld.jar 
+7
source share

The easiest way, and the one I always use, is to define an object (like you), but not the corresponding companion class. In this case, the Scala compiler will create a couple of classes, one whose name is exactly the same as the object, will contain static transfer methods, which for the purpose of entry points into the launcher is exactly what you need. Another class has the name of your object with $ added and where the code is located. Javap will reveal these things if you are interested in learning more.

Thus, your HelloWorld example will work the way you want, which allows you to:

% scala pkg.package.more.HelloWorld args that you will ignore

Randall Schulz

+3
source share

Did you also define the class HelloWorld ? There is a bug in Scala 2.7.x that prevents the creation of static methods of the HelloWorld class when both the object HelloWorld and the class HelloWorld defined.

0
source share

All Articles