How to write a desktop / standalone application in Scala?

An student asked this question to me a while ago, and I figured it might be valid for other people starting with Scala as well. So I’ll try to give general directions in this post.

The idea is not to write a full tutorial; instead, I’ll show you the possible paths you have.

First, the basics. In Java, when we want to have a standalone application, we have an structure similar to the following:

public class Main {
  public static void main(String args[]) {
    System.out.println("Hello World!");
  }
}

Since Scala also runs on top of the Java Virtual Machine, the structure will  be similar, with a few tweaks. The first one is related to the fact that Scala doesn’t have static fields, so we will have to use an object.

The second tweak is that we won’t even need the main method – we will use an utility class that have that method and it will call the code we pass to the object constructor. This is what the result looks like:

object Main extends App {
  println("Hello World!")
}

In practical terms, both versions will work the same way – but as always, the Scala version will be much simpler. We could also directly implement the main method in the Scala version, instead of extending App, but I’ll left that as an exercise to the reader.

The next question could be: how to write user interfaces with Scala?

The answer to this question is very direct as well: the same way we would write UIs in Java. For example, the following code uses Java Swing to create a simple window application:

import javax.swing._

object Main extends App {
  val frame = new JFrame("Hello World!")
  frame.setSize(300, 300)
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
  frame.setVisible(true)
}

The code above is a direct translation from what a Java version would be. It leaves a bit to be desired, so if you want more, you can take a look at Scala Swing – which is a set of wrappers on top of the Java Swing API, to make it easier to use.

Another option is to follow the new trend in Java land: Java FX. You can use Java FX directly from Scala, or use a set of wrappers called Scala FX – whatever suits you better.

I hope I made it clear how you could start coding a desktop and / or standalone application in Scala. If not, please let me know.

Advertisements
This entry was posted in java, scala and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s