Introduction to Kotlin Collections and Strings

Introduction

Welcome to this course! Our goal is to strengthen your understanding of Kotlin by revisiting its basics and preparing you for interviews. In this lesson, we will explore collections—specifically, the types of lists in Kotlin, namely mutable and immutable lists, as well as how to work effectively with strings.

Lists in Kotlin at a Glance

Kotlin offers two flavors of lists, each serving different needs:

  • Immutable Lists: Lists where the elements cannot be changed after their creation.
  • Mutable Lists: Lists where you can change, add, or remove elements freely.

Immutable Lists

Here's how you can use immutable lists in Kotlin:

Kotlin
fun main() {
    // Creating an Immutable List
    val list = listOf("apple", "banana", "cherry")

    // Accessing elements using indexing
    val firstElement = list[0] // 'apple'
    val lastElement = list[list.size - 1] // 'cherry'

    // Getting the size of the list
    val size = list.size // 3

    // Printing the list
    println(list) // prints [apple, banana, cherry]
}

Immutable lists are perfect for use cases where you don't need to modify the contents of the list after its creation. You can find more information in the Kotlin documentation for Immutable Lists.

Mutable Lists

If you need to modify your list, mutable lists are the way to go. Mutable lists support all the operations available for immutable lists, with additional methods for modification:

Kotlin
fun main() {
    // Creating a Mutable List
    val mutableList = mutableListOf("apple", "banana", "cherry")

    // Adding elements
    mutableList.add("date") // adds 'date'

    // Removing elements
    mutableList.remove("banana") // removes 'banana'

    // Accessing sublist
    val sublist = mutableList.subList(1, mutableList.size) // ["cherry", "date"]

    // Finding the index of an element
    val index = mutableList.indexOf("cherry") // 1

    // Sorting the list
    val sortedList = mutableList.sorted() // ["apple", "cherry", "date"]

    // Printing the list
    println(mutableList) // prints [apple, cherry, date]
}

Mutable lists provide flexibility by allowing modification of the list elements even after its creation. Explore more about them in the Kotlin documentation for Mutable Lists.

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