该tail
方法返回一个由除第一个元素(基本上是 )之外的所有元素组成的集合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" |
+------------------+------------------------+-------------------------------+
请注意,这两种方法也适用于String
类型。
回答@Leandro 问题:是的,我们可以这样做,如下所示:
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()