Introduction

Welcome to the next unit of this course!

Before we delve deeper into Scala essentials for interview preparation, we'll revisit some Scala features — specifically, Scala collections like Lists and Strings. These collections allow Scala to group multiple elements, such as numbers or characters, under a single entity.

Some of these concepts might already be familiar to you, so feel free to breeze through the beginning until we reach the main topics.

Understanding Scala's Collections

As a starting point, it's crucial to understand what Scala's collections are. They help us manage multiple values efficiently and are categorized into various types such as Lists, Sets, and Maps.

We will focus mainly on Lists and Strings. An interesting point is that Lists are immutable by default, meaning they are unchangeable after creation. However, Scala offers mutable collections if changes are required. Let's see some examples:

object Solution {
  def main(args: Array[String]): Unit = {
    // Defining a list and a string
    val myList = List(1, 2, 3, 4)
    val myString = "hello"

    // Attempting to change the first element of both collections won't work for immutable lists
    // Uncommenting the below line will result in an error
    // myList(0) = 100

    // Strings in Scala, like Java, are immutable
    // myString(0) = 'H' // Would also result in an error
  }
}
Diving Into Lists

Imagine having to take an inventory of all flora in a forest without a list — seems near impossible, right? That's precisely the purpose Lists serve in Scala. They allow us to organize data so that each item holds a definite position or an index, facilitating access to or modification of individual items.

However, to modify Lists in Scala, you may use ListBuffer, which provides a mutable version:

import scala.collection.mutable.ListBuffer

object Solution {
  def main(args: Array[String]): Unit = {
    // Creating a list
    val fruits = ListBuffer("apple", "banana", "cherry")

    // Add a new element at the end
    fruits += "date" // ListBuffer("apple", "banana", "cherry", "date")

    // Inserting an element at a specific position
    fruits.insert(1, "bilberry") // ListBuffer("apple", "bilberry", "banana", "cherry", "date")

    // Removing a particular element
    fruits -= "banana" // ListBuffer("apple", "bilberry", "cherry", "date")

    // Accessing elements using indexing
    val firstFruit = fruits(0) // "apple"
    val lastFruit = fruits.last // "date"
  }
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal