Start learning free

LESSON 11 OF 348 · VARIABLES

Variable Naming Rules in Scala in Scala

Lesson

TL ; DR:

  • In Scala, we use the camelCase convention to name our variables. It implies separating different words with capital letters, like this:

    val companyName = "Apple"
    
    val foundingYear = 1976
    
    val isUnicorn = true
    
    val numberOfEmployees = 137000
    



Full lesson:

Variable names must consist ONLY of letters, numbers and underscores and they must start with a letter or underscore.

Bad variable names:

val 18spam = 1
val x.15 = "hello"
val #name = true

If you try to create a variable with any of these names, Scala will throw an error.


Naming conventions: camelCase and snake_case

Sometimes a variable name might consist of multiple words, for example if you want to store the first name of a person. You might be tempted to separate those names by whitespaces, like this:

val first name = "Kate"

This code will also throw an error.

When you name your variables, you want to use one of these two conventions:

snake_case = separate different words with an underscore (_), like this:

val first_name = "Jane"
val last_name = "Doe"

camelCase = separate different words with capital letters, like this:

val firstName = "Jane"
val lastName = "Doe"

It's important to be consistent with the casing technique you use. Do not combine both of them in the same code, like this:

val first_name = "Jane"
val lastName = "Doe"

Case sensitive:

Variable names are case sensitive:

val name = "Kate"
val Name = "Andy"
val NAME = "George"

println(name + " " + Name + " " + NAME) // Output: Kate Andy George

Although Scala allows us to do this, it's always confusing and a bad coding practice to differentiate variable names just by case!


Mnemonic Variable Names:

Since we programmers are given a choice in how we choose our variable names, there is a bit of "best practice".

Sometimes we want them short like x and y, but sometimes we want them descriptive, especially if they are important.

Here is a great example:

val a = 25
val b = 13
val c = a * b
println(c)

compared to:

val hours = 25
val rate = 13
val pay = hours * rate
println(pay)

Scala understands and is happy with both of these pieces of code. But it's clearly which version makes your reader happier.


Assignment
Follow the Coding Tutorial and let's let's name some variables well!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    Variable Naming Rules 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