Skip to content

Scala Basic Syntax

Scala syntax borrows from Java but adds functional elements and aims for conciseness. Key differences include optional semicolons, type inference, and expression-oriented programming.

  • Object: An instance of a class, having state (fields) and behavior (methods).
  • Class: A blueprint for creating objects.
  • Method: A function associated with a class or object, defining behavior.
  • Field: A variable associated with a class instance or object, defining state (val or var).

Scala 3 introduced the @main annotation as a simple way to create an executable program without needing an explicit object and main method.

// Save as HelloWorld.scala
@main def helloWorld(): Unit = {
println("Hello, Scala 3 world!")
}

While you can use scalac and scala commands for single files, using a build tool like sbt is standard for projects.

Using scalac/scala (for simple files):

$ scalac HelloWorld.scala # Compiles to .class files
$ scala helloWorld # Runs the main function (name after @main)

Using sbt (Recommended for projects):

# Assuming HelloWorld.scala is in src/main/scala and you have a build.sbt
$ sbt compile # Compiles the project
$ sbt run # Compiles if needed, then runs the main class found

You can still use the traditional object with a main method signature:

// Save as LegacyHello.scala
object LegacyHello {
def main(args: Array[String]): Unit = {
println("Hello from traditional main!")
// Access command-line arguments via 'args' array
// println(s"Arguments: ${args.mkString(", ")}")
}
}

Run with sbt run or scala LegacyHello arg1 arg2.

  • Case Sensitivity: Scala is case-sensitive (Hello is different from hello).
  • Naming Conventions: - Classes/Traits/Objects: UpperCamelCase (e.g., MyClass, LoggerObject). - Methods/Fields/Variables: lowerCamelCase (e.g., myMethod, userName). - Constants (val often used): Can be UpperCamelCase or UPPER_SNAKE_CASE.
  • File Names: Should typically match the name of a class or object defined within, ending with .scala (e.g., MyClass.scala).
  • Entry Point: Execution starts from a method annotated with @main or a standard def main(args: Array[String]): Unit method within an object.
  • Semicolons (;): Generally optional at the end of lines. Required only to separate multiple statements on the same line.
  • Blocks ({}): Used to group multiple statements, forming the body of methods, classes, expressions (like if, match, for). The value of a block is the value of its last expression.

Names given to classes, methods, variables, etc. Scala has several types:

Starts with a letter or underscore (_), followed by letters, digits, or underscores. Cannot use reserved keywords. $ is reserved.

Valid: `age`, `salary`, `_temp`, `process_data`, `Var1`
Invalid: `1stValue`, `my-var`, `$amount`

Consists of one or more operator characters (e.g., +, -, *, /, :, ?, ~, #). Often used for symbolic method names.

Valid: `+`, `++`, `::`, `/:`, `->`, `?`

An alphanumeric identifier followed by _ and an operator identifier. Used for defining unary operators or assignment operators.

Valid: `unary_+` (defines prefix `+`), `vector_+=` (defines `+=` operator)

An arbitrary string enclosed in backticks (`). Allows using reserved keywords as identifiers or identifiers with special characters.

Valid: `` `type` ``, `` `yield` ``, `` `My Var With Spaces` ``

Reserved words that cannot be used as identifiers (unless enclosed in backticks).

Common keywords: abstract, case, catch, class, def, do, else, enum, export, extends, false, final, finally, for, given, if, implicit, import, lazy, match, new, null, object, override, package, private, protected, return, sealed, super, then, this, throw, trait, true, try, type, val, var, while, with, yield.

(Note: This list includes keywords from different Scala versions, e.g., Scala 3 keywords like enum, given, export, then).

  • Single-line: Start with //. The rest of the line is ignored.
// This is a single-line comment
val x = 10 // Comment after code
  • Multi-line: Start with /* and end with */. Can span multiple lines. Can be nested.
/* This is a
multi-line comment.
/* Nested comments are allowed */
*/
val y = 20
  • Scaladoc: Start with /** and end with */. Used for generating API documentation.
/** Adds two integers.
*
* @param a The first integer.
* @param b The second integer.
* @return The sum of a and b.
*/
def add(a: Int, b: Int): Int = a + b

Organize code into namespaces using packages. Use the import keyword to access members from other packages.

package com.mycompany.myapp // Package declaration at the top
// Import specific members
import scala.util.Try
import java.io.File
// Import all members of a package (wildcard)
import scala.collection.mutable._
// Import multiple members from the same package
import scala.concurrent.{ Future, ExecutionContext }
// Import with renaming
import java.util.{ HashMap => JavaHashMap }
class MyCode {
val buffer: Buffer[Int] = Buffer(1, 2, 3) // Using imported Buffer
val future: Future[String] = Future.successful("Done")
val javaMap = new JavaHashMap[String, Int]()
}