Scala Cheat Sheet
Hello World:
object HelloWorld {
def main(args: Array[String]): Unit = {
println("Hello, World!")
}
}
Variables:
// Mutable variable
var age: Int = 25
// Immutable variable
val pi: Double = 3.14159
// Type inference
val name = "John Smith"
Data Types:
// Numeric types
val number: Int = 10
val floatingPoint: Double = 3.14
// Boolean type
val isTrue: Boolean = true
// String type
val text: String = "Hello, World!"
// Collection types
val array: Array[Int] = Array(1, 2, 3, 4, 5)
val list: List[Int] = List(1, 2, 3, 4, 5)
val set: Set[Int] = Set(1, 2, 3, 4, 5)
val map: Map[String, Int] = Map("key1" -> 1, "key2" -> 2)
Operators:
// Arithmetic operators
val sum: Int = 5 + 3
val difference: Int = 10 - 4
val division: Double = 15 / 2
val remainder: Int = 15 % 2
val product: Int = 4 * 6
// Comparison operators
val isEqual: Boolean = 5 == 5
val isGreater: Boolean = 10 > 5
val isLessThanOrEqual: Boolean = 15 <= 20
// Logical operators
val logicalAnd: Boolean = true && false
val logicalOr: Boolean = true || false
val logicalNot: Boolean = !true
Conditional Statements:
// If statement
val condition: Boolean = true
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
// Match expression
val day: Int = 3
day match {
case 1 => println("Monday")
case 2 => println("Tuesday")
case 3 => println("Wednesday")
case _ => println("Invalid day")
}
Loops:
// For loop
for (i <- 1 to 5) {
println(i)
}
// While loop
var count: Int = 0
while (count < 5) {
println(count)
count += 1
}
// Do-while loop
var count: Int = 0
do {
println(count)
count += 1
} while (count < 5)
// Foreach loop
val numbers: List[Int] = List(1, 2, 3, 4, 5)
numbers.foreach { number =>
println(number)
}
Functions:
// Function declaration
def functionName(parameters: Type): ReturnType = {
// Code to execute
}
// Function with return type inference
def add(a: Int, b: Int) = a + b
// Function call
val result: Int = functionName(arguments)
Classes and Objects:
// Class declaration
class MyClass {
// Class fields
var myField: Int = 0
// Class methods
def myMethod(): Unit = {
println("My method")
}
}
// Object declaration (Singleton)
object MyObject {
// Object fields
val myField: Int = 10
// Object methods
def myMethod(): Unit = {
println("My method")
}
}
// Creating an instance of a class
val myObject: MyClass = new MyClass()
// Accessing class fields and methods
myObject.myField = 5
myObject.myMethod()
// Accessing object fields and methods
val value: Int = MyObject.myField
MyObject.myMethod()