Scala Get First and Last elements of List using Pattern Matching

In case you missed the obvious:

case list @ (head :: tail) if head == list.last => true

The head::tail part is there so you don’t match on the empty list.


Use the standard :+ and +: extractors from the scala.collection package


ORIGINAL ANSWER

Define a custom extractor object.

object :+ {
  def unapply[A](l: List[A]): Option[(List[A], A)] = {
    if(l.isEmpty)
      None
    else 
      Some(l.init, l.last)
  }
}

Can be used as:

val first :: (l :+ last) = List(3, 89, 11, 29, 90)
println(first + " " + l + " " + last) // prints 3 List(89, 11, 29) 90

(For your case: case x :: (_ :+ y) if(x == y) => true)