List Operations (head/tail/map/filter)
In this page:
List Operations (head/tail/map/filter)
.head returns a list's first element (throwing if the list is empty), and .tail returns every element after the first as a new list. .map(f) transforms every element and returns a new list of results, and .filter(p) keeps only elements matching a predicate. These are the fundamental building blocks for working with immutable lists functionally.
Warning: Calling .head or .tail on an empty list throws a NoSuchElementException/UnsupportedOperationException -- check .isEmpty or use .headOption first if unsure.
Example: List Operations (head/tail/map/filter)
object Main extends App {
val numbers = List(1, 2, 3, 4, 5)
println(numbers.head)
println(numbers.tail)
val doubled = numbers.map(n => n * 2)
val evens = numbers.filter(n => n % 2 == 0)
println(doubled)
println(evens)
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: