Scala Basic Syntax
Scala Basic Syntax
Section titled “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.
Core Concepts Review:
Section titled “Core Concepts Review:”- 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 (
valorvar).
First Scala Program (@main):
Section titled “First Scala Program (@main):”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!")}Compilation and Execution:
Section titled “Compilation and Execution:”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 foundTraditional main Method (Still Valid):
Section titled “Traditional main Method (Still Valid):”You can still use the traditional object with a main method signature:
// Save as LegacyHello.scalaobject 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.
Basic Syntax Rules:
Section titled “Basic Syntax Rules:”- Case Sensitivity: Scala is case-sensitive (
Hellois different fromhello). - Naming Conventions:
- Classes/Traits/Objects: UpperCamelCase (e.g.,
MyClass,LoggerObject). - Methods/Fields/Variables: lowerCamelCase (e.g.,myMethod,userName). - Constants (valoften 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
@mainor a standarddef main(args: Array[String]): Unitmethod within anobject. - 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 (likeif,match,for). The value of a block is the value of its last expression.
Identifiers:
Section titled “Identifiers:”Names given to classes, methods, variables, etc. Scala has several types:
Alphanumeric:
Section titled “Alphanumeric:”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`Operator:
Section titled “Operator:”Consists of one or more operator characters (e.g., +, -, *, /, :, ?, ~, #). Often used for symbolic method names.
Valid: `+`, `++`, `::`, `/:`, `->`, `?`Mixed:
Section titled “Mixed:”An alphanumeric identifier followed by _ and an operator identifier. Used for defining unary operators or assignment operators.
Valid: `unary_+` (defines prefix `+`), `vector_+=` (defines `+=` operator)Literal:
Section titled “Literal:”An arbitrary string enclosed in backticks (`). Allows using reserved keywords as identifiers or identifiers with special characters.
Valid: `` `type` ``, `` `yield` ``, `` `My Var With Spaces` ``Scala Keywords:
Section titled “Scala Keywords:”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).
Comments:
Section titled “Comments:”- Single-line: Start with
//. The rest of the line is ignored.
// This is a single-line commentval 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 + bPackages and Imports:
Section titled “Packages and Imports:”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 membersimport scala.util.Tryimport java.io.File
// Import all members of a package (wildcard)import scala.collection.mutable._
// Import multiple members from the same packageimport scala.concurrent.{ Future, ExecutionContext }
// Import with renamingimport 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]()}