๐ Scala Cheatsheet - Essential Syntax & Commands
๐ ๏ธ Setup & Running
scala: Start REPL (interactive shell)
scalac MyFile.scala: Compile Scala file
scala MyFile: Run compiled class
scala MyFile.scala: Run script directly
๐ Variables & Data Types
val x = 10: Immutable value
var y = 20: Mutable variable
val name: String = “Scala”: Explicit type
Common types: Int, Double, Boolean, String, Unit, Any
๐ฆ Collections
Lists: val nums = List(1, 2, 3)
Sets: val items = Set(“a”, “b”)
Maps: val m = Map(“a” -> 1, “b” -> 2)
Arrays: val arr = Array(1, 2, 3)
๐งฎ Operators
Arithmetic: +, -, *, /, %
Comparison: ==, !=, >, <, >=, <=
Logical: &&, ||, !
๐ Control Flow
If/Else: if (x > 0) println(“Positive”) else println(“Negative”)
Match (like switch): x match { case 1 => “One”; case _ => “Other” }
For loop: for (i <- 1 to 5) println(i)
๐ Functions
Basic: def add(a: Int, b: Int): Int = a + b
Anonymous: val add = (a: Int, b: Int) => a + b
๐งฑ Classes & Objects
Class: class Person(val name: String, val age: Int)
Object (Singleton): object Hello { def main(args: Array[String]): Unit = println(“Hello, Scala”) }
๐งฌ Case Classes & Pattern Matching
Case Class: case class User(name: String, age: Int)
Pattern Matching: user match { case User(name, age) => println(s"Hi $name") }
๐ Higher-Order Functions
Map: List(1, 2, 3).map(_ * 2)
Filter: List(1, 2, 3).filter(_ % 2 == 1)
Reduce: List(1, 2, 3).reduce(_ + _)
๐งต Traits (Interfaces)
Define Trait: trait Greeter { def greet(): Unit }
Use Trait: class Person extends Greeter { def greet(): Unit = println(“Hello!”) }
๐ ๏ธ SBT (Simple Build Tool)
sbt: Open sbt shell
sbt compile: Compile project
sbt run: Run main class
sbt test: Run tests
build.sbt: name := “MyApp” scalaVersion := “2.13.12”