Start learning free

LESSON 10 OF 414 · VARIABLES

Data Types in Scala: Int, Double, String, Boolean and Char

Lesson Read the full explanation

TL ; DR:

In Scala, not all data is treated the same. There are different data types, such as:

  • Int - represents integer numbers like 3 and -12

  • Double - represents floating point numbers like 3.14

  • String - represents a string (sequence of characters) like "John Doe"

  • Boolean - represents data that can have one of two values: true or false

  • Char - represents a single character like 'a', 'Z' or '?'



Full lesson:

One instruction can have several distinct meanings depending on the data types it's working with.

For example, suppose you see this line of code somewhere in a program:

println(a + b)

Can you tell for sure what it does without knowing anything about the variables a and b?

It might add two numbers, if a and b are both numbers:

var a = 10
var b = -5

println(a + b) // Output: 5

But it also might concatenate two strings, if a and b are both strings:

var a = "Hello "
var b = "world!"

println(a + b) // Output: Hello world!

Of course, addition and string concatenation are two completely different operations and Scala needs to figure out which one to do.

And this is exactly why Scala assesses the data type of every value you use in your program. In order to be able to make these decisions when needed.

In our example, when it reads a + b, Scala checks the data type of a and b. If both are strings, it performs string concatenation. If both are numbers, it performs addition.


Invalid operations:

Asessing data types is also helpful for Scala to make sure that what you do with the data actually makes sense.

For example, computers can perform mathematical operations on numbers, but not on strings. Of course, nobody can stop you from writing a program like this:

var a = "peanut"
var b = "butter"

println(a * b) // Compile error

But when you try to compile this program, Scala will refuse and report a type mismatch error: Found: (b : String), Required: Int. (The * on a string expects an Int, a repeat count, as in "ab" * 3.)

This is the way of Scala telling you: "Hey, I'm a little confused. How do you multiply two strings? I've never heard of that."


Assignment
Follow the Coding Tutorial and let's practice with data types!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    SCALA · VARIABLES

    Data Types in Scala, explained

    Why types exist

    Every value in Scala has a data type, and the compiler knows it before the program runs. The type decides what operations make sense. Take this line:

    println(a + b)
    

    If a and b are numbers, + adds them. If they are strings, + joins them:

    val a = 10
    val b = -5
    println(a + b)          // 5
    
    val c = "Hello "
    val d = "world!"
    println(c + d)          // Hello world!
    

    The same symbol does different jobs because Scala looks at the types. The types also catch nonsense early. Multiplying two strings has no meaning, and the compiler refuses:

    val x = "peanut"
    val y = "butter"
    println(x * y)
    
    -- [E007] Type Mismatch Error ---------------------------------------------
      |  println(x * y)
      |              ^
      |              Found:    (y : String)
      |              Required: Int
    

    A String can be multiplied by an Int, which repeats it, so "ab" * 3 is "ababab". A string on the right is what the compiler can't accept. The program doesn't run at all; this is a compile-time error, not a crash in the middle of execution.

    The basic types

    TypeHoldsExamples
    Intwhole numbers3, -12
    Doublenumbers with a decimal point3.14, -0.5
    Stringtext"John Doe"
    Booleantrue or falsetrue, false
    Charone character'a', '?'

    Some details that matter:

    • String versus Char. Strings use double quotes and chars use single quotes. "a" is a string with one character, and 'a' is a Char. They are different types.
    • Int has limits. It uses 32 bits, so it covers about plus or minus 2.1 billion. Going past the top wraps around silently: Int.MaxValue + 1 is -2147483648. For bigger whole numbers use Long.
    • Whole numbers and decimals are separate. 7 / 2 is 3 because both sides are Int, while 7 / 2.0 is 3.5.
    • Booleans are lowercase. true and false are written in lowercase.

    Declaring a type

    You can state a variable's type after its name, separated by a colon: val myInt: Int = 5. Scala can often work the type out from the value, so val myInt = 5 would also be an Int. Writing the type makes the intention visible, and the compiler checks the value against it.

    The exercise step by step

    1. An integer. Create myInt with type Int and give it a whole number such as 5.
    2. A decimal. On the next line create myFloat with type Double. The name says float, but in Scala the usual decimal type is Double, so the value is something like 3.14. Keep myInt above it.
    3. Text. Create myString with type String and a value in double quotes.
    4. A yes or no. Create myBool with type Boolean and set it to true or false. Keep the three earlier lines.

    The solution in Scala

    val myInt: Int = 5
    val myFloat: Double = 3.14
    val myString: String = "Hello"
    val myBool: Boolean = true
    

    Each line follows the same pattern: val, the name, a colon, the type, an equals sign and a value. val means the name can't be assigned a different value later. Scala also has a type called Float, with less precision than Double, and a decimal literal such as 3.14 is a Double unless it ends in f, as in 3.14f. The variable name myFloat is only a name; its declared type is what counts.

    Common mistakes

    • A value that doesn't match the type. val myInt: Int = 3.14 is a compile error, because Scala does not cut a decimal down to a whole number for you. The error shows Found: Double and Required: Int.
    • Forgetting quotes. val myString: String = Hello makes Scala look for a name called Hello.
    • Single quotes for text. 'Hello' is not a valid Char, because a Char holds exactly one character.
    • Capitalised booleans. True is not a Scala keyword. Write true.
    • Removing earlier lines. Later steps keep the earlier variables, so add new lines instead of replacing old ones.

    Key takeaways

    • Every value has a type, and Scala checks types while compiling.
    • The basic types are Int, Double, String, Boolean and Char.
    • The type follows the name after a colon, and the value must match it.
    • The same operator can mean different things for different types, and some combinations are rejected.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free