Scala for Beginners: How to Define Variables

Learn how to declare values and variables the idiomatic way in Scala — immutability first.


Introduction

Before you build classes, objects, or APIs, you need to understand the most basic building block: variables.

Scala makes a big deal about immutability, and this starts with how you declare data.

Let’s walk through the difference between val and var — and when to use them.


val – Immutable Value

val name = "Alice"
val age = 30
  • ✅ Think of val like a final variable in Java or a const in JavaScript.
  • ❌ You cannot reassign a val.
// This will cause a compilation error:
name = "Bob" // ❌ reassignment to val
  • ✅ Use val by default — it makes your code safer and easier to reason about.

var – Mutable Variable

var count = 1
count = count + 1
  • You can reassign var as needed.

Type Inference (and Explicit Types)

Scala can often infer the type of a value based on the assigned data:

val city = "Mumbai"   // Inferred as String
val score = 4.5       // Inferred as Double

But you can also write the type explicitly when you want to be more specific or improve readability:

val city: String = "Mumbai"
val score: Double = 4.5

This is especially useful in function signatures, public APIs, or when collaborating in a team.

Summary

KeywordMutable?Recommended?Use When
val❌ No✅ Yes (default)When the value should not change
var✅ Yes❌ Only when neededWhen you need to reassign the value
0
Subscribe to my newsletter

Read articles from Saiprasad Vyawahare directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Saiprasad Vyawahare
Saiprasad Vyawahare