Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 37 ยท Getting Started

Syntax Rules and Comments

Learn Scala 3 syntax basics: significant indentation vs braces, blocks as expressions, naming rules and conventions, keywords, comments and Scaladoc documentation.

Scala's syntax looks small on the surface but has a few rules that surprise newcomers: indentation can replace braces, a block returns its last expression, and many characters are allowed in names. This lesson gives you the vocabulary you need to read any Scala file. Examples are read-only Scala with a runnable Java or Kotlin comparison where it helps.

Statements, lines and semicolons

A Scala statement normally ends at the end of the line. You do not write semicolons, though they are legal if you want two statements on one line:

SCALA
val a = 1
val b = 2; val c = 3

A line that is obviously unfinished continues on the next one. If the line ends with an operator or an open parenthesis, the compiler keeps reading:

SCALA
val total = 10 +
  20 +
  30

The trap is a line that already looks complete. In the next snippet, the second line is a separate statement, not a continuation:

SCALA
val wrong = 10
  + 20      // a new expression statement; `wrong` is just 10

Put the operator at the end of the first line, or wrap the whole thing in parentheses.

Blocks: indentation or braces

Scala 3 lets you open a block by indenting after a colon-like construct. Both of these are valid:

SCALA
// indentation style (Scala 3)
def describe(n: Int): String =
  val kind = if n % 2 == 0 then "even" else "odd"
  s"$n is $kind"

// braces style (works in Scala 2 and 3)
def describe2(n: Int): String = {
  val kind = if (n % 2 == 0) "even" else "odd"
  s"$n is $kind"
}

Pick one style per project. The indentation style is the default in new Scala 3 code, and tools such as scalafmt can convert between them. Use spaces, normally two per level. Mixed tabs and spaces lead to confusing errors.

The last expression is the result

The value of a block is the value of its last expression. describe above never writes return. That final s"$n is $kind" is the result. Idiomatic Scala avoids return completely, because it behaves oddly inside lambdas.

Compare with Kotlin, where an expression body works similarly:

Kotlin A block's last expression (Kotlin comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Names (identifiers)

Names in Scala may contain letters, digits, underscores and, when written in backticks or following operator rules, symbols.

  • Start with a letter or underscore, not a digit: count1 is fine, 1count is not.
  • Case matters: Total and total are different.
  • Convention. camelCase for values and methods (userName, parseLine), PascalCase for classes, traits and objects (UserAccount), UPPER_CASE rarely, mainly for constants in some codebases (Scala style prefers PascalCase for constants too, such as MaxRetries).
  • Operator names like +, ::, ++ and <=> are just method names made of symbols.
SCALA
val userName = "ada"
class UserAccount
val MaxRetries = 3

If you need a reserved word or an odd name, wrap it in backticks:

SCALA
val `type` = "book"     // `type` is a keyword

Keywords

Hard keywords cannot be used as names (unless in backticks). The ones you will meet first:

Group Keywords
Declarations val, var, def, class, object, trait, enum, type, given, extension
Control if, then, else, match, case, for, do, while, yield, try, catch, finally, return, throw
Modifiers abstract, final, sealed, override, lazy, private, protected, implicit
Other new, this, super, import, package, extends, with, true, false, null

Words such as using, open, inline, end, opaque and transparent are "soft" keywords: they act as keywords only in certain positions, so old code that used them as names still compiles.

Optional end markers

For long blocks, Scala 3 lets you close them with an explicit marker to make the structure obvious:

SCALA
class Counter:
  var n = 0
  def next(): Int =
    n += 1
    n
  end next
end Counter

end markers are optional and mostly useful when a block is longer than a screenful.

Comments

Scala has the same comment forms as Java:

SCALA
// a single-line comment

/* a block comment
   spanning lines */

/** Scaladoc: documents the next definition.
  *
  * @param name the name to greet
  * @return the greeting text
  */
def greet(name: String): String = s"Hello, $name"

Block comments can be nested, so you can comment out a region of code that already contains a /* ... */ comment. That is a small but real improvement over Java.

Scaladoc

Scaladoc comments start with /**. Tools such as sbt doc and scala-cli doc turn them into HTML. Common tags are @param, @return, @throws, @see and @example. Scaladoc supports Markdown-like wiki syntax in Scala 3, so backticks and lists work. Put a one-sentence summary first, then details.

Here is the same documented helper in Java so you can see Javadoc, which Scaladoc mirrors:

Java Javadoc, Scaladoc's cousin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Literals at a glance

SCALA
42          // Int
42L         // Long
3.14        // Double
3.14f       // Float
'x'         // Char
"text"      // String
true        // Boolean
()          // Unit, the only value of type Unit
1_000_000   // underscores for readability
0xFF        // hexadecimal, 255

We examine the types properly in values, variables and types.

Style tips

  • Two-space indentation, one statement per line.
  • No return and no semicolons.
  • Keep lines under roughly 100 characters.
  • Let scalafmt format your code so style arguments disappear.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the result of a Scala block such as { val a = 1; a + 1 }?

    A block evaluates to its last expression, so no return is needed.
  2. 2. Which is the usual naming convention for a class?

    Classes, traits and objects use PascalCase; values and methods use camelCase.
  3. 3. How can you use a reserved word such as type as a name?

    Backticks turn any text into a legal name, for example type.
  4. 4. Which comment form is used to produce API documentation?

    Scaladoc comments start with /** and are rendered to HTML by documentation tools.

Summary

  • Statements end at the line end; semicolons are optional.
  • Blocks use indentation or braces, and a block's value is its last expression.
  • Follow the naming conventions: camelCase for values/methods, PascalCase for types.
  • Backticks allow reserved words as names; end markers close long blocks.
  • Use //, /* */ (nestable) and /** */ Scaladoc.

Next: Values, Variables and Types