The Scala documentation says that Scala objects can call Java objects and vice-versa. I wanted to write a code snippet to see how a Java application can create and call Scala objects. It's very basic but it works!
A Java class "Zoo" with the "main" method creates a Scala object "Dog" and calls its method "talk".
Running the Zoo main on Windows:
C:\ScalaTest>java Zoo
Zoo...
Woof, woof!
Here it is the code for the 2 files Zoo.java and Dog.scala:
Zoo.java:
class Zoo {
public static void main(String[] args)
{
System.out.println("Zoo...");
Dog dog = new Dog();
dog.talk();
} // main
} // class Zoo
Dog.scala:
class Dog
{
val sound = "Woof, woof!"
def talk() = println(sound)
} // class Dog
How to build it on Windows:
Compile the Scala file first:
C:\ScalaTest>scalac Dog.scala
Then compile the main app, Java will find the Dog.class
C:\ScalaTest>javac Zoo.java
Run it:
C:\ScalaTest>java Zoo
Zoo...
Woof, woof!
"Zoo" is printed by the Java Zoo class
"Woof, woof" is printed by the Scala "Dog" class.
That's it!
Preliminary steps to install Java and Scala:
- install a JDK (download it from http://java.sun.com/javase/downloads)
- add the path to your java \bin folder (something like C:\jdk1.5.0_09\bin) to your PATH environment variable.
- check that the Java compiler is accessible by opening a cmd window an typing "javac" and return. A list of options will be displayed, starting like this: "Usage: javac
. - add the Java libraries to the "classpath" environment variable, something like this: "classpath=.;C:\jdk1.5.0_09\jre\lib\rt.jar;C:\jdk1.5.0_09\lib\tools.jar;"
- install Scala (download it from http://www.scala-lang.org/)
- add the Scala bin folder to your PATH environment variable. Should look like this: "...;C:\scala-2.6.0-final\bin;"
- add the Scala libraries to the "classpath" environment variable. Should look like this with the Java libraries: "classpath=.;C:\jdk1.5.0_09\jre\lib\rt.jar;C:\jdk1.5.0_09\lib\tools.jar;C:\scala-2.6.0-final\lib\scala-library.jar;"
- check that the Scala compiler is accessible from a cmd window: "C:\ScalaTest>scalac" will display a list of options: "Usage: scalac
..."
That should do it. If not, check java.sun.com for Java installation issues and scala-lang.org for the Scala ones.
I am off to try some Actors code in Scala.