Get head item and tail items from scala list

前端 未结 2 646
北海茫月
北海茫月 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条回答
  •  走了就别回头了
    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)
    

提交回复
热议问题