Get head item and tail items from scala list

前端 未结 2 645
北海茫月
北海茫月 2021-01-03 22:59

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         


        
相关标签:
2条回答
  • 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()
    
    0 讨论(0)
  • 2021-01-03 23:26

    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)
    
    0 讨论(0)
提交回复
热议问题