x match { case 1 => println("One") case 2 => println("Two") case _ => println("Other")}
Functions
// Basic functiondef add(a: Int, b: Int): Int = a + b// Function with default parametersdef greet(name: String = "World"): Unit = println(s"Hello, $name!")// Anonymous functionval square: Int => Int = x => x * x// Function as a parameterdef operate(a: Int, b: Int, func: (Int, Int) => Int): Int = func(a, b)
Collections
Lists
val nums = List(1, 2, 3)nums.map(_ * 2).filter(_ > 2)
Arrays
val arr = Array(1, 2, 3)arr.foreach(println)
Maps
val map = Map("a" -> 1, "b" -> 2)map("a") // Access value
Sets
val set = Set(1, 2, 3)set.contains(2)
Object-Oriented Programming
Classes
class Person(val name: String, var age: Int) { def greet(): String = s"Hello, $name"}
Objects
object SingletonObject { def greet(): Unit = println("Singleton greeting!")}
Companion Objects
class Person(val name: String)object Person { def apply(name: String): Person = new Person(name)}val p = Person("John") // Calls apply
Traits and Mixins
trait Greeter { def greet(): Unit = println("Hello!")}class Person extends Greeter
Pattern Matching
val value: Any = 42value match { case i: Int if i > 0 => println("Positive Integer") case s: String => println("String") case _ => println("Other")}
Error Handling
try { val result = 10 / 0} catch { case e: ArithmeticException => println("Cannot divide by zero")} finally { println("Execution complete")}