Collections · 23 of 42

Arrays

  • Arrays are constructed simply using Array(element1, element2, ...)
  • Arrays in Scala map to Java primitive Arrays (e.g. Java’s int[] is Scala’s Array[Int], Java’s String[] is Array[String] in Scala)
  • Arrays are mutable (can’t change their size once created, but can modify their elements)
  • Since they are using Java’s arrays, to print an Array’s content nicely, use .mkString(",")
  • Array elements can be of any type, but the Array’s final type will be the lowest common denominator

    class Foo(val value1:Int)
    class Bar(value1:Int, val value2:Int) extends Foo(value1)
    val list:Array[Foo] = Array(new Foo(1), new Bar(2,3))
    
def printArray[K](array:Array[K]) = array.mkString("Array(" , ", " , ")")

//Mutable array of type Array[Int]
val array1 = Array(1, 2, 3)
printArray(array1)
//Mutable array of type Array[Any]
val array2 = Array("a", 2, true)
printArray(array2)
//Mutable array of type Array[String]
val array3 = Array("a", "b", "c")
printArray(array3)
//Access items using (index) not [index]
val itemAtIndex0 = array3(0)

//Modify items the same way
array3(0) = "d"
printArray(array3)

//Concatenation using the ++ operator,
//Prepending items using +: and appending using :+
val concatenated = "prepend" +: (array1 ++ array2) :+ "append"
printArray(concatenated)

//Finding an index of an item
array3.indexOf("b")

//Diff
val diffArray = Array(1,2,3,4).diff(Array(2,3))
printArray(diffArray)

//Find (stops when item is found)
val personArray = Array(("Alice",1), ("Bob",2), ("Carol",3))
def findByName(name:String) = personArray.find(_._1 == name).getOrElse(("David",4))
val findBob = findByName("Bob")
val findEli = findByName("Eli")

val bobFound = findBob._2
val eliFound = findEli._2

Contents

Scala basics

  1. Overview
  2. Scalculator
  3. Operators are methods
  4. Variables
  5. Final variables
  6. Printing values
  7. String interpolation
  8. String formatting
  9. Useful operations
  10. Method definition
  11. Method definition 2
  12. Method definition 3
  13. Anonymous functions
  14. Anonymous functions 2
  15. Return multiple values
  16. Declare multiple variables
  17. Assign multiple variables
  18. Loops using while
  19. Loops using for
  20. Loops without loops
  21. If
  22. Match as a switch
  23. Arrays
  24. Lists
  25. Sets
  26. Maps
  27. Mutable collections
  28. Collections: accessing elements
  29. Collections: concatenation
  30. Mutable collection operations
  31. Immutable collections with var
  32. Collections: useful methods
  33. Classes
  34. Classes, continued

What's new in Scala 3

  1. Scala 3: what changed
  2. Optional braces & new control syntax
  3. Top-level definitions & @main
  4. Enums & ADTs
  5. Extension methods
  6. given & using
  7. Union & intersection types
  8. Smaller niceties