Is there a method in scala to get the (single) head element of a List or Seq and the (collection) tail of the list? I know there\'s
def splitAt(n: Int): (Lis
The tail
method returns a collection consisting of all elements except the first one (which is basically the head
).
+------------------+------------------------+-------------------------------+
| Input | head | tail |
+------------------+------------------------+-------------------------------+
| List() | NoSuchElementException | UnsupportedOperationException |
| List(1) | 1 | List() |
| List(1, 2, 3, 4) | 1 | List(2, 3, 4) |
| "" | NoSuchElementException | UnsupportedOperationException |
| "A" | 'A' (char) | "" |
| "Hello" | 'H' | "ello" |
+------------------+------------------------+-------------------------------+
Note that the two methods apply to String
type as well.
Answering @Leandro question: Yes we can do that, as shown below:
scala> var a::b::c = List("123", "foo", 2020, "bar")
a: Any = 123
b: Any = foo
c: List[Any] = List(2020, bar)
scala> var a::b::c = List("123", "foo", "bar")
a: String = 123
b: String = foo
c: List[String] = List(bar)
scala> var a::b::c = List("123", "foo")
a: String = 123
b: String = foo
c: List[String] = List()
You can use pattern matching:
val hd::tail = List(1,2,3,4,5)
//hd: Int = 1
//tail: List[Int] = List(2, 3, 4, 5)
Or just .head/.tail methods:
val hd = foo.head
// hd: Int = 1
val hdOpt = foo.headOption
// hd: Option[Int] = Some(1)
val tl = foo.tail
// tl: List[Int] = List(2, 3, 4)