Rewriting Java in Scala & Making Code Lovely 3 – Variable Declarations

I thought I'd take a step back and look at how variables are declared in Scala and how it compares with Java.

Local Variables

In Java you declare a local variable like this:

Map<String, Integer> userIds = new HashMap<String, Integer>();
In Scala, it is a lot shorter:
var userIds = new HashMap[String, Integer]
The type of the variable is missing. This is because Scala can calculate the type. In this case it will calculate that userIds is of type HashMap[String, Integer]. The Scala site has more information on how it calculates the types (this is called type inference).

Another minor detail here is that you use square brackets [ ] instead of angle brackets < > to specify generics.


In the above example we declared userIds with the keyword 'var'. This makes it a variable - we can change userIds to point at a different HashMap if we want.

In Java we can say that a variable is constant using the final keyword:

final int x = 4;
x = 5; // Compile error: cannot change x

Scala doesn't have the final keyword when declaring variables. Instead, you use the 'val' keyword:

val x = 4
x = 5 // Compile error: cannot change x

This has a benefit that isn't obvious.

Every time you declare a variable you specify whether you can change it or not.

There are many good reasons to make something constant (or, immutable as many people like to say). However, in Java it is easy to forget to make something immutable, it is also a burden as you have to write more every time you want to keep something constant. In Scala, you make an active choice every time you declare a variable. It is also easy for constants to be the default that you use.

Specifying Types

Sometimes, you may want to specify the type of a variable. This is easy:

val x : Int = 4
val name : String = "Bob"

Normally, you won't need to do this. Only when you have a specific type requirement or Scala has failed to infer the types - a rare event!


You've now been introduced to variable declarations. Scala improves this basic area of programming in a number of ways:

  • Reduces repetitiveness by not writing types all the time
  • Makes the choice of constant/not constant an active choice
  • Makes it easier to alter types of variables

The next part of this series will follow on from this and take a look at declaring fields in classes.


blog comments powered by Disqus

Colin Howe

I'm Colin. I like coding, ultimate frisbee and startups. I am VP of engineering at Conversocial