Using Java code from Scala is fairly easy. This is because both languages are based on JVM. Using Scala code in Java is also possible but trickier. In general, Scala is designed to be compatible with Java. You can take advantage of this if you want to use one of the many available Java libraries. For example, you could use Java's Swing library to write a user interface for your program, or you may want to use Java's useful JFreeChart to perform data visualization or just basic plotting. All Java concepts translate more or less directly to the Scala concepts. We will look into that in one of the chapters of this book. For now, let's consider a really simple Scala program just to see how easy it is to write user interfaces with Swing in Scala. You can type the following into a script and then run it on Unix-like systems. You may have to modify the shell name and parameters:
#!/bin/sh exec scala "$0" "$@" !# import javax.swing.JFrame object GUIHelloWorld extends App { val f = new JFrame f.setVisible(true) f.setTitle("Hello, world!") f.setSize(300, 200) f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) } HelloWorld.main(args)
We will discuss using other Java libraries in Chapter 8, Scientific Plotting with Scala.