Skip to main content

Posts

Operations on list in Scala, Part - 1

In Scala, a List is a fundamental data structure that represents an ordered collection of elements. Lists are immutable, which means that once a list is created, its elements cannot be changed. Here are some common operations you can perform on Scala lists: 1. Creating Lists: You can create a list in Scala using the List companion object: scala Copy code val myList: List[Int] = List(1, 2, 3, 4, 5) 2. Accessing Elements: You can access elements in a list using their indices: scala Copy code val firstElement = myList(0) // Returns 1 val secondElement = myList(1) // Returns 2 3. Concatenation: You can concatenate two lists using the ++ operator: scala Copy code val anotherList: List[Int] = List(6, 7, 8) val combinedList = myList ++ anotherList // Returns List(1, 2, 3, 4, 5, 6, 7, 8) 4. Adding Elements: You can add elements to the beginning of a list using :: (cons) operator: scala Copy code val newList = 0 :: myList // Returns List(0, 1, 2, 3, 4, 5) 5. List Operations: head : Returns