Scala
Updated: September 10, 2025Categories: Languages
Printed from:
Scala Cheatsheet
Language Overview
Scala is a modern, multi-paradigm programming language that combines object-oriented and functional programming paradigms. Designed to express common programming patterns concisely, Scala runs on the Java Virtual Machine (JVM) and is fully interoperable with Java.
Key Features:
- Statically typed with powerful type inference
- Supports both object-oriented and functional programming
- Runs on JVM with seamless Java interoperability
- Immutability and functional programming constructs
- Concise syntax with advanced type system
Basic Syntax
Hello World
Scala
123456object HelloWorld { def main(args: Array[String]): Unit = { println("Hello, Scala!") } }
Comments
Scala
123456789101112// Single-line comment /* Multi-line comment */ /** * ScalaDoc comment * Used for generating documentation */
Data Types
Primitive Types
Scala
123456789101112131415// Numeric Types val byte: Byte = 127 val short: Short = 32767 val int: Int = 2147483647 val long: Long = 9223372036854775807L val float: Float = 3.14f val double: Double = 3.14159 // Boolean and Character val bool: Boolean = true val char: Char = 'A' // String val str: String = "Scala"
Collection Types
Scala
1234567891011// Immutable Collections val list: List[Int] = List(1, 2, 3) val set: Set[String] = Set("a", "b", "c") val map: Map[String, Int] = Map("one" -> 1, "two" -> 2) // Mutable Collections import scala.collection.mutable val mutableList = mutable.ListBuffer(1, 2, 3) val mutableSet = mutable.Set("a", "b") val mutableMap = mutable.Map("one" -> 1)
Variables and Constants
Scala
1234567891011// Immutable variable (recommended) val immutableVar: Int = 42 // Mutable variable var mutableVar: String = "Hello" mutableVar = "World" // Type inference val inferredInt = 10 // Type is inferred as Int val inferredString = "Scala" // Type is inferred as String
Operators
Arithmetic Operators
Scala
123456val sum = 5 + 3 // Addition val diff = 10 - 4 // Subtraction val prod = 3 * 6 // Multiplication val div = 15 / 3 // Division val mod = 10 % 3 // Modulus
Comparison Operators
Scala
1234567val isEqual = (5 == 5) // Equality val isNotEqual = (5 != 3) // Inequality val greaterThan = 10 > 5 // Greater than val lessThan = 3 < 7 // Less than val greaterOrEqual = 5 >= 5 // Greater or equal val lessOrEqual = 3 <= 4 // Less or equal
Logical Operators
Scala
1234val andOp = true && false // Logical AND val orOp = true || false // Logical OR val notOp = !true // Logical NOT
Control Structures
Conditional Statements
Scala
12345678910111213141516// If-Else if (condition) { // code block } else if (anotherCondition) { // another code block } else { // default block } // Pattern Matching val result = someValue match { case 1 => "One" case 2 => "Two" case _ => "Other" }
Loops
Scala
123456789101112131415161718192021222324// For Loop for (i <- 1 to 5) { println(i) } // For Loop with Guard for (i <- 1 to 10 if i % 2 == 0) { println(i) // Prints even numbers } // While Loop var x = 0 while (x < 5) { println(x) x += 1 } // Do-While Loop var y = 0 do { println(y) y += 1 } while (y < 5)
Functions
Basic Function Definition
Scala
123456789101112def add(a: Int, b: Int): Int = { a + b } // Function with default parameter def greet(name: String = "World"): String = { s"Hello, $name!" } // Multiple parameter lists def multiply(x: Int)(y: Int): Int = x * y
Lambda Functions (Anonymous Functions)
Scala
1234val square = (x: Int) => x * x val numbers = List(1, 2, 3, 4) val squared = numbers.map(square)
Higher-Order Functions
Scala
123456def operate(f: (Int, Int) => Int, x: Int, y: Int): Int = { f(x, y) } val sum = operate(_ + _, 5, 3) // Returns 8
Object-Oriented Programming
Classes and Objects
Scala
1234567891011// Class definition class Person(val name: String, var age: Int) { def introduce(): String = s"Hi, I'm $name and I'm $age years old" } // Creating an object val john = new Person("John", 30) // Case Class (immutable, with automatic methods) case class Point(x: Int, y: Int)
Traits (Similar to Interfaces)
Scala
12345678910111213trait Logger { def log(message: String): Unit } class ConsoleLogger extends Logger { def log(message: String): Unit = println(message) } // Multiple trait inheritance trait Drawable extends Logger { def draw(): Unit }
Error Handling
Try-Catch-Finally
Scala
1234567891011import scala.util.{Try, Success, Failure} def divide(a: Int, b: Int): Try[Int] = Try { a / b } divide(10, 0) match { case Success(value) => println(s"Result: $value") case Failure(exception) => println(s"Error: ${exception.getMessage}") }
Option for Null Safety
Scala
123456val someValue: Option[Int] = Some(42) val noneValue: Option[Int] = None someValue.map(_ * 2) // Some(84) noneValue.getOrElse(0) // 0
File I/O
Scala
12345678910111213import scala.io.Source import java.io.{File, PrintWriter} // Reading a file val source = Source.fromFile("example.txt") val lines = source.getLines().toList source.close() // Writing to a file val writer = new PrintWriter(new File("output.txt")) writer.write("Hello, Scala!") writer.close()
Functional Programming Concepts
Immutable Collections
Scala
12345val numbers = List(1, 2, 3, 4, 5) val doubled = numbers.map(_ * 2) val filtered = numbers.filter(_ % 2 == 0) val reduced = numbers.reduce(_ + _)
For-Comprehensions
Scala
12345val result = for { x <- List(1, 2, 3) y <- List(4, 5, 6) } yield x * y
Concurrent Programming
Futures
Scala
1234567891011import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global val futurecalculation = Future { // Long-running computation Thread.sleep(1000) 42 } futureCalculation.map(_ * 2)
Common Libraries and Frameworks
Standard Library
scala.collection: Immutable and mutable collectionsscala.concurrent: Futures and parallel processingscala.io: File and I/O operations
Popular Third-Party Libraries
- Akka: Concurrent and distributed computing
- Play Framework: Web application framework
- Spark: Big data processing
- Cats: Functional programming library
- Scalaz: Functional programming extensions
Best Practices
Code Style
- Prefer immutability
- Use pattern matching
- Leverage type inference
- Write pure functions
- Use Option instead of null
Performance Tips
- Use lazy evaluation
- Minimize object creation
- Use specialized collections
- Leverage parallel collections
- Avoid excessive allocation
Build and Dependency Management
- Use SBT (Scala Build Tool)
- Manage dependencies with Maven or Coursier
- Use Scala version management tools
Testing
- ScalaTest: Popular testing framework
- Specs2: Another testing library
- Property-based testing with ScalaCheck
Resources for Further Learning
- "Programming in Scala" by Martin Odersky
- Scala Documentation: https://docs.scala-lang.org
- Coursera Scala Specialization
- Scala Exercises: https://www.scala-exercises.org
- Functional Programming in Scala by John A. De Goes
Continue Learning
Discover more cheatsheets to boost your productivity