HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to ScalaVariables (val / var)Data TypesStringsListsConditions (if / match)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables & Types
🔢 Numbers & Math
✍️ String
📚 Collection
🔀 Condition & Loop
🧩 Function
Scala›Variables (val / var)

Variables (val / var)

Immutable values with val, mutable values with var; type inference and naming.

Simple enough for a 5-year-old to understand

val: immutable value

In Scala, values defined with val cannot be reassigned. In a functional style, val is preferred first.

Example code
1
val name = "Alex"
The type automatically becomes String.
VariableThe type automatically becomes String.
2
println(name)
Alex writes.
Output / InputAlex writes.
VariableOutput / Input
💡 Hint: val is assigned once; if you try to change it, you get a compilation error.

var: mutable value

Example code
1
var score = 10
Numeric variable.
VariableNumeric variable.
2
score = 20
Since it is a var, it can be changed.
VariableSince it is a var, it can be changed.
3
println(score)
Writes 20.
Output / InputWrites 20.
VariableOutput / Input

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Which one is used for a definition whose value will not change later?

About this topic

There are two ways to store values in Scala: val and var. A name defined with val receives a value once and cannot be changed; a name defined with var can be reassigned. This distinction is the most visible part of the language's functional side.

The community's common recommendation is to use val by default. The core idea of functional programming is to produce new values instead of mutating state; val enforces this discipline at the smallest unit of code.

Scala usually infers the type from the initial value. If you want to write the type explicitly, you use a colon; this is recommended especially in public interfaces because it provides information to the reader.

What you will learn

  • the difference between val and var
  • Type inference and explicit type declaration
  • Defining a lazy value
  • Naming conventions
  • why immutability is preferred

Who is this for?

  • Beginners to Scala
  • those switching from Java who are looking for the final keyword
  • Those who want to acquire functional coding habits

When to use?

Everything that remains constant throughout the flow, such as a calculation result, configuration value, and data coming into a function, should be val.

Using a lazy definition for values that are expensive to compute and might never be used completely eliminates unnecessary work.

Common mistakes

Wrong

val toplam = 10
toplam = 20

A name defined with val cannot be reassigned; the compiler gives a "Reassignment to val" error. This is the equivalent of the final keyword in Java, but in Scala it is used as the default choice. If you are going to change the value, you must write var.

Correct

var toplam = 10
toplam = 20

Wrong

val liste = scala.collection.mutable.ListBuffer(1, 2)
liste += 3
println(liste)

There is no error here, but there is a conceptual confusion: val only prevents the name from being rebound, it does not freeze the contents of the object it points to. Even if a mutable collection is defined with val, its contents can change. For true immutability, an immutable collection type should be used.

Correct

val liste = List(1, 2)
val yeni = liste :+ 3
println(yeni)

Wrong

var sayi: Int = null

Int is a value type and does not accept null; a "type mismatch" error is thrown. In Scala, Option is used for values that can be null. This is an important choice that makes null-pointer errors visible in the type system and separates it from Java.

Correct

var sayi: Option[Int] = None

Frequently asked questions

Should I use val or var?

The rule is simple: write val first, switch to var if the compiler forces you to. Unchanging values make code easier to follow and eliminate an entire class of bugs in concurrent code.

What is the purpose of a lazy value?

It ensures that the value is not calculated until its first use. If an expensive resource is never used, it is never created; if it is used, it is calculated once and cached. It is a common pattern in configuration and connection objects.

Should I always write the type?

It is not needed for local variables, type inference is sufficient. However, writing it in public method signatures is recommended: it both serves as documentation and defines a stable interface for library users.

Summary

val cannot be reassigned, var can be assigned.

val does not freeze the contents of the object.

Value types do not accept null values.

Option is used for values that can be null.

Lazy values are calculated upon first use.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code