Scala Cheat Sheet

Here’s a Scala cheat sheet covering some fundamental concepts and syntax:

Scala Basics

Hello World:

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println("Hello, World!")
  }
}

Variable Declaration:

val immutableVariable: Int = 42
var mutableVariable: String = "Scala"

Data Types:

val intNumber: Int = 42
val doubleNumber: Double = 3.14
val booleanValue: Boolean = true
val stringValue: String = "Scala"

Control Structures

If-Else:

val x = 10
val result = if (x > 5) "Greater than 5" else "Less than or equal to 5"

For Loop:

for (i <- 1 to 5) {
  println(s"Value of i: $i")
}

While Loop:

var count = 0
while (count < 5) {
  println(s"Count: $count")
  count += 1
}

Functions

Function Declaration:

def add(x: Int, y: Int): Int = {
  x + y
}

Anonymous Functions (Lambda):

val multiply = (x: Int, y: Int) => x * y

Higher-Order Functions:

def operate(x: Int, y: Int, operation: (Int, Int) => Int): Int = {
  operation(x, y)
}

val result = operate(3, 4, (a, b) => a + b)

Collections

Lists:

val numbersList = List(1, 2, 3, 4, 5)

Maps:

val person = Map("name" -> "John", "age" -> 30)

Tuples:

val myTuple = (1, "Scala", 3.14)

Object-Oriented Programming

Classes and Objects:

class Person(name: String, age: Int) {
  def displayInfo(): Unit = {
    println(s"Name: $name, Age: $age")
  }
}

val person = new Person("Alice", 25)
person.displayInfo()

Inheritance:

class Student(name: String, age: Int, rollNumber: Int) extends Person(name, age)

Traits:

trait Speaker {
  def speak(): Unit
}

class EnglishSpeaker extends Speaker {
  def speak(): Unit = {
    println("Speaking English")
  }
}

Pattern Matching

Matching on Values:

val day = "Monday"
val message = day match {
  case "Monday" | "Tuesday" => "Start of the week"
  case "Friday" => "TGIF"
  case _ => "Other day"
}

Matching on Types:

def matchType(x: Any): String = x match {
  case s: String => "String"
  case i: Int => "Int"
  case _ => "Other"
}

This Scala cheat sheet covers basic syntax, control structures, functions, collections, object-oriented programming, and pattern matching.