Learn Scala 3 Fast: Explicitly Declaring The Data Type

In the previous examples I created string and integer variables like this:

val name = "Fred"     // String
val count = 1         // Int (an integer)

On the human side this syntax is nice because it’s concise, and any programmer that has a little experience can tell that the name field contains a string and count contains an integer.

On the computer side, what happens here is that Scala is smart enough to implicitly know those data types, i.e., that "Fred" has the type String and 1 has the type Int. Back in the old days we had to manually declare these things, but there’s no reason to do this any more.

Expressiveness

This syntax is also great because there are no extra characters to read! In other languages you have to type something like this to say the same thing:

final int count = 1;    // other languages

Instead, I would much rather read this Scala code:

val count = 1

As you’ll see throughout this book, Scala is a “concise but readable” language, meaning that there are no wasted characters. There are just enough characters, but no more than that. Because of this, we call Scala expressive.

Because programmers spend roughly ten times as much time reading code as we do writing code, an expressive language is a very good thing.

Explicitly declaring the data type

That being said, there are also times when it will be helpful to explicitly specify the data type of a variable. In those cases you specify the type after the variable name, like this:

val name: String = "John Doe"

In this specific example there’s no reason to do this, but once I show more data types in the coming lessons, you’ll see situations where this can be helpful. For now, all you need to know is that when you want to declare the variable’s data type, this is the syntax you use:

val name:     String     = "John Doe"
    ----      ------       ----------
    the       the          the
    variable  variable     variable
    name      type         value

As another example, these are the two ways you create an Int (integer) variable in Scala:

val answer = 42          // implicit format
val answer: Int = 42     // explicit format

As you can see, there is no need to explicitly declare the variable type in these examples. Adding the type just makes your code more verbose, and in general, being a verbose programming language is bad — verbose is harder to read.

When you want to explicitly declare the type when using a var, use the same syntax.

Exercises

The exercises for this lesson are available here.