Home »
Scala
Scala Cheatsheet
By IncludeHelp Last updated : October 13, 2024
Scala Hello World
The first Scala program is to print "Hello World" on the screen. You can print it by using the println() method:
Below is an example of printing Hello World in Scala:
object HelloWorld {
def main(args: Array[String]) = {
println("Hello, world")
}
}
Variable Declarations
There are two types of variables: mutable and immutable. Immutable variables are known as constants.
Variable (mutable)
The mutable variable can be declared using the var keyword.
Below is an example of a variable declaration:
var age = 10
var name = "Alvin Alexander"
Constant (immutable)
The immutable variable, also known as a constant, can be declared using the val keyword.
Below is an example of a constant declaration:
val age = 10
val name = "Alvin Alexander"
Printing Text
To print text, you can use the following methods:
- print(): It prints a line of text.
- println(): It prints a line of text followed by a newline.
- printf(): It prints the formatted text. You can use the format specifiers to print different types of values.
Example of these methods:
object HelloWorldExample {
def main(args: Array[String]): Unit = {
print("Hello, World! ")
println("Hello, World!")
printf("%s\n", "Hello, World!")
}
}
User Input
To get user input, you need to use the scala.io.StdIn object and its methods such as readLine(), readInt(), readDouble(), etc., to take different types of inputs.
Below is an example of user input in Scala:
import scala.io.StdIn
object ExampleUserInput {
def main(args: Array[String]): Unit = {
// String input
println("Enter your name: ")
val name = StdIn.readLine()
// Integer input
println("Enter your age: ")
val age = StdIn.readInt()
// Double input
println("Enter your salary: ")
val salary = StdIn.readDouble()
// Displaying the user inputs
println(s"Hello, $name! You are $age years old, and your salary is $salary.")
}
}
Data Types
Scala provides a rich set of data types, including value types, reference types, and special types.
1. Value (Primitive) Data Types
The following are the list of value (primitive) data types:
Data Type |
Description |
Example |
Byte |
8-bit signed integer |
val b: Byte = 100 |
Short |
16-bit signed integer |
val s: Short = 10000 |
Int |
32-bit signed integer |
val i: Int = 100000 |
Long |
64-bit signed integer |
val l: Long = 100000L |
Float |
32-bit floating-point number |
val f: Float = 10.5f |
Double |
64-bit floating-point number |
val d: Double = 10.5 |
Char |
16-bit Unicode character |
val c: Char = 'A' |
Boolean |
Represents a true or false value |
val bool: Boolean = true |
Unit |
Represents no value (similar to void in other languages) |
val u: Unit = () |
2. Reference (Objects) Data Types
The following is the list of reference (object) types in Scala:
- String: It is used to define an object of string type.
- Array: It is used to define an object of an Array (similar type of data types).
- List: It is used to define an object of the Linked List type.
- Option: It is used to define an option that may or may not exist. It can be null or none.
- Tuple: It is used to define an object of Tuple type. It is a fixed-size collection of different value types.
3. Special Data Types
The following are the special data types:
Data Type | Description | Example |
Any |
All type of scala inherits from Any. |
AnyVal, AnyRef |
Null |
It represents a Null type. |
println(Null) |
Nothing |
It represents a nothing type. |
println(Noting) |
Nil |
It represents an empty object i.e., a Nil. |
println(Nil) |
Example of Scala Data Types
object ExampleDataTypes {
def main(args: Array[String]): Unit = {
// Primitive types
val age: Int = 10
val salary: Double = 1234.5
val isActive: Boolean = false
// Reference types
val name: String = "Alvin"
val scores: Array[Int] = Array(10, 20, 30)
val person: (String, Int) = ("Alvin", 32) // Tuple
val status: Option[String] = Some("Active")
// Output the values
println(s"Name: $name, Age: $age, Salary: $salary, Active: $isActive")
println(s"Scores: ${scores.mkString(", ")}")
println(s"Person: Name = ${person._1}, Age = ${person._2}")
println(s"Status: ${status.getOrElse("Unknown")}")
}
}
Output
Name: Alvin, Age: 10, Salary: 1234.5, Active: false
Scores: 10, 20, 30
Person: Name = Alvin, Age = 32
Status: Active
Type Casting
Type casting is the process of converting that type from one to another. For example, we can convert int type to float type in Scala.
1. Implicit type casting
object MyClass {
def main(args: Array[String]): Unit = {
val a: Int = 3421
println("a has value: " + a + " and its type is: " + a.getClass)
val c = a / 4 // result is 855.25 but will be converted to Int
println("The value of a/4: " + c + " and its type is: " + c.getClass)
}
}
2. Explicit Type Casting
object MyClass {
def main(args: Array[String]): Unit = {
// Type conversion from Short to Long
val a: Short = 3421
println("a has value: " + a + " and its type is: " + a.getClass)
val b: Long = a // converting type from short to long
println("Type casting from Short to Long")
println("b has value: " + b + " and its type is: " + b.getClass)
// Type conversion from Char to Float
val ch: Char = 'S'
println("\nch has value: " + ch + " and its type is: " + ch.getClass)
val fl: Float = ch // converting type from Char to Float
println("Type casting from Character to Float")
println("fl has value: " + fl + " and its type is: " + fl.getClass)
}
}
Loops
1. Using range
for(w <- range){
// Code..
}
2. Using to
for( w <- 0 to 10){
println(w);
}
3. Using until
for( w <- 0 until 10){
println(w);
}
Strings
Scala strings can be created using the object of a String class.
Below is an example of the string:
var str: String = "Hello, Scala!"
1. String concatenation
You can concatenate the strings using the plus (+) operator.
Below is an example of string concatenation:
var greet = "Hello, " + "Alvin!"
println(greet) // Output: Hello, Alvin!
2. String interpolation
String interpolation allows you to put variables to display their value inside a string.
Below is an example of string interpolation in Scala:
var name = "Alvin"
var age = 28
println(s"My name is $name and I am $age years old.")
3. Accessing Characters
To access characters of the string using the index values. Index starts with 0 to string length -1. You can also use the string.charAt() method.
Here is an example of accessing characters in a string:
val str = "Hello"
val firstChar = str(0) // Prints 'H'
val secondChar = str.charAt(1) // Prints 'e'
4. String Length
To get the length of the string, you can use the string.length property.
Below is an example of getting string length:
val str = "Hello, World!"
println(str.length) // Output: 13
Arrays
Scala arrays are mutable in nature and can group similar types of data items.
1. Array with Initial Values
To create an array with an initial value, use the Array() method and provide the value.
Below is an example of array initializing with values:
val arr = Array(1, 2, 3, 4, 5)
2. Accessing and Modifying Array Elements
You can access or modify elements in an array using its index values.
Below is an example of accessing array elements and modifying the values:
val arr = Array(10, 20, 30, 40)
println(arr(2)) // Output: 30
arr(0) = 50 // changing the first element
println(arr.mkString(", ")) // Output: 50, 20, 30, 40
3. Iterating over an Array
Use the for loop and the foreach() method to iterate over array elements.
Below is an example of iterating over an array of elements:
val arr = Array(1, 2, 3, 4, 5)
// Using for loop
for (elem <- arr) {
println(elem)
}
// Using foreach() method
arr.foreach(println)
4. Array Length
You can get the length (or size) of an array using length.
Below is an example of getting array length:
val arr = Array(1, 2, 3, 4, 5)
println(arr.length) // Output: 5
5. Concatenating Arrays
Use the plus (+) operator to concatenate two arrays.
Below is an example of concatenating array elements:
val arr1 = Array(10, 20)
val arr2 = Array(30, 40)
val result = arr1 ++ arr2
println(result.mkString(", ")) // Output: 10, 20, 30, 40
User-defined Functions
You can define your own functions (also known as methods) to perform specific tasks.
1. Function definition
def functionName(parameter1: DataType1, parameter2: DataType2, ...): ReturnType = {
// Function body
// Return value
}
2. Function without Parameters
def greet(): String = {
"Hello, Alvin!"
}
println(greet()) // Output: Hello, Alvin!
3. Function with Parameters
def add(a: Int, b: Int): Int = {
a + b
}
println(add(10, 20)) // Output: 30
4. Function with Default Parameters
def greet(name: String = "Default Name"): String = {
s"Hello, $name!"
}
println(greet()) // Output: Hello, Default Name!
println(greet("Alvin")) // Output: Hello, Alvin!
5. Function with Variable-length Arguments (Varargs)
def printNumbers(numbers: Int*): Unit = {
numbers.foreach(println)
}
printNumbers(1, 2, 3, 4, 5)
// Output:
// 1
// 2
// 3
// 4
// 5
Recursive Functions
A function that calls itself is known as a recursive (or recursion) function. Here is an example of a function that calculates the factorial of a number:
def factorial(n: Int): Int = {
if (n == 0) 1
else n * factorial(n - 1)
}
println(factorial(5)) // Output: 120
Anonymous Functions (Lambdas)
Scala allows you to define anonymous functions, the functions that do not have any name. These are also called lambda expressions. The syntax is:
(val1: DataType1, val2: DataType2, ...) => { expression }
Here is an example of an anonymous function that adds two numbers:
val add = (a: Int, b: Int) => a + b
println(add(10, 20)) // Output: 30
Classes and Objects
Scala supports both object-oriented and functional programming paradigms. A class defines the blueprint for objects, and an object is an instance of a class.
Below is an example of a Scala class and object:
// Define a class Person
class Person(val name: String, val age: Int) {
// Method to print name and greeting message
def greet(): Unit = {
println(s"Hello, my name is $name and I am $age years old.")
}
}
object Main {
def main(args: Array[String]): Unit = {
val person = Person("Alice", 30)
person.greet()
// Output: Hello, my name is Alice and I am 30 years old.
}
}
Traits
Scala traits are like interfaces in other languages; traits can contain both abstract and concrete methods. A trait is used to share fields and methods between classes.
Below is an example of Scala traits:
trait Iterator[A] {
def hasNext: Boolean
def next(): A
}
class IntIterator(to: Int) extends Iterator[Int] {
private var current = 0
override def hasNext: Boolean = current < to
override def next(): Int = {
if (hasNext) {
val t = current
current += 1
t
} else 0
}
}
val iterator = new IntIterator(10)
iterator.next() // returns 0
iterator.next() // returns 1
Pattern Matching
Scala pattern matching is used for checking a value against a pattern.
Below is an example of pattern matching:
val number = 3
number match {
case 1 => println("One")
case 2 => println("Two")
case 3 => println("Three")
case _ => println("Other number")
}
Options
The option is a container that contains one single value, which can be one of the two distinct values.
Below is an example of Scala options:
object Demo {
def details(x: Option[String]) = x match {
case Some(s) => s
case None => "?"
}
def main(args: Array[String]) {
val student = Map("name" -> "Ram", "standard" -> "10")
println("show(student.get( \"name\")) : " + details(student.get( "name")) )
println("show(student.get( \"percentage\")) : " + details(student.get( "percentage")) )
}
}