Scala Get First and Last elements of List using Pattern Matching

后端 未结 4 932
故里飘歌
故里飘歌 2020-12-16 00:02

I am doing a pattern matching on a list. Is there anyway I can access the first and last element of the list to compare?

I want to do something like..



        
4条回答
  •  被撕碎了的回忆
    2020-12-16 01:00

    simply:

    case head +: _ :+ last => 
    

    for example:

    scala> val items = Seq("ham", "spam", "eggs")
    items: Seq[String] = List(ham, spam, eggs)
    
    scala> items match {
         |   case head +: _ :+ last => Some((head, last))
         |   case List(head) => Some((head, head))
         |   case _ => None
         | }
    res0: Option[(String, String)] = Some((ham,eggs))
    

提交回复
热议问题