Python to Scala Collections Translation
Collection Creation
Lists
# Python
empty = []
nums = [1, 2, 3]
repeated = [0] * 5
from_range = list(range(1, 11))
// Scala
val empty = List.empty[Int] // or List[Int]()
val nums = List(1, 2, 3)
val repeated = List.fill(5)(0)
val fromRange = (1 to 10).toList
Dictionaries → Maps
# Python
empty = {}
person = {"name": "Alice", "age": 30}
from_pairs = dict([("a", 1), ("b", 2)])
// Scala
val empty = Map.empty[String, Int]
val person = Map("name" -> "Alice", "age" -> 30)
val fromPairs = List(("a", 1), ("b", 2)).toMap
Sets
# Python
empty = set()
nums = {1, 2, 3}
from_list = set([1, 2, 2, 3])
// Scala
val empty = Set.empty[Int]
val nums = Set(1, 2, 3)
val fromList = List(1, 2, 2, 3).toSet
Transformation Operations
Map
# Python
doubled = [x * 2 for x in nums]
doubled = list(map(lambda x: x * 2, nums))
// Scala
val doubled = nums.map(_ * 2)
val doubled = nums.map(x => x * 2)
Filter
# Python
evens = [x for x in nums if x % 2 == 0]
evens = list(filter(lambda x: x % 2 == 0, nums))
// Scala
val evens = nums.filter(_ % 2 == 0)
val evens = nums.filter(x => x % 2 == 0)
Reduce/Fold
# Python
from functools import reduce
total = reduce(lambda a, b: a + b, nums)
total = sum(nums)
product = reduce(lambda a, b: a * b, nums, 1)
// Scala
val total = nums.reduce(_ + _)
val total = nums.sum
val product = nums.foldLeft(1)(_ * _)
// Use foldLeft when you need an initial value