package com.vff.lessons import scala.collection.GenTraversable import scala.collection.GenTraversableOnce /** * In functional-style Scala, Collections are processed * by splitting a list into its head and tail, where * head is the first element and tail is all other elements. * <p> * This is very useful and often used in Pattern Matching. * */ object ListHeadAndTail extends App { // Create our list. val list = List(1, 2, 3, 4, 5, 6) // Output the contents of head (1st item) and then tail (rest of the items). println("list.head = " + list.head) println("list.tail = " + list.tail) // Simple recursion. def display[A](s: Seq[A]): Unit = { // Here is our pattern matching: s match { // case of an empty list case Nil => println("End of list") /* match the case where list is not empty - get first item and * recurse with new list containing the rest of the items - by * default scala collection classes will be immutable. */ case head :: tail => println("Got element - " + head); display(tail) } } display(list) }
Output:
list.head = 1 list.tail = List(2, 3, 4, 5, 6) Got element - 1 Got element - 2 Got element - 3 Got element - 4 Got element - 5 Got element - 6 End of list