Start learning free

LESSON 10 OF 348 · VARIABLES

Data Types in Scala in Scala

Lesson

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) // TypeError

But when you try to run this program, Scala will throw a TypeError: bad operand types for binary operator '*'.

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

    Data Types in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free