Scala Lesson 3 – Scala Syntax | Dataplexa

Scala Basic Syntax

In this lesson, you will learn the basic syntax of Scala. Understanding Scala syntax is essential because it combines ideas from both object-oriented programming and functional programming.

Scala syntax is designed to be concise, expressive, and readable. Once you understand the fundamentals, writing Scala code becomes natural and efficient.


Scala Is Expression-Based

One important concept in Scala is that almost everything is an expression. An expression returns a value.

Even simple operations like conditions and blocks return results.

val x = 10 + 20
x

Here, the expression 10 + 20 returns a value that is stored in x.


Statements vs Expressions

In many languages, there is a clear difference between statements and expressions. In Scala, this difference is minimal.

For example, an if block returns a value:

val result = if (5 > 3) "Yes" else "No"
result

The if expression evaluates to either "Yes" or "No".


Semicolons Are Optional

Scala does not require semicolons at the end of statements. The compiler automatically detects line endings.

val a = 10
val b = 20
val sum = a + b

You may use semicolons, but it is recommended to avoid them for clean code.


Using val and var

Scala uses val and var to define variables.

  • val creates an immutable value
  • var creates a mutable variable
val name = "Scala"
var version = 3

version = 4

Using val is preferred whenever possible.


Code Blocks

A block in Scala is a group of expressions enclosed in braces { }. The value of the last expression becomes the value of the block.

val total = {
  val x = 10
  val y = 20
  x + y
}

total

This feature is commonly used in functions and conditional logic.


Comments in Scala

Comments are used to explain code and improve readability. Scala supports both single-line and multi-line comments.

// This is a single-line comment

/*
This is a
multi-line comment
*/

Printing Output

Scala uses println() to display output to the console.

println("Hello, Scala!")

This is helpful for debugging and testing code.


Why Syntax Matters

Clean syntax improves:

  • Code readability
  • Maintainability
  • Team collaboration

Scala’s syntax allows you to write powerful programs with less code.


📝 Practice Exercises


Exercise 1

Create a variable using val and assign a number to it.

Exercise 2

Write an if expression that returns a string.

Exercise 3

Create a code block that adds two numbers.


✅ Practice Answers


Answer 1

val number = 100

Answer 2

val message = if (10 > 5) "Greater" else "Smaller"

Answer 3

val sum = {
  val a = 5
  val b = 7
  a + b
}

What’s Next?

In the next lesson, you will learn about variables in Scala, including immutability and best practices.

This is a core concept that strongly influences Scala programming style.