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): (List[A], List[A])
and I can easily grab the single item from the first list of the tuple. But is there any built in method that is basically this?
def splitAtHead: (Option[A], List[A])
Like I said, you can easily chain splitAt
to return the right signature, but I figured a built in method might be able to save an intermediate tuple.
Edit:
@om-nom-nom's answer is correct, but this is why I couldn't use his 2nd version.
List[S](s1, s2, s3, s4).sortBy { _.f (h) } match {
case hd :: tail => recurse(tail)
}
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)
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()