Skip to content

Instantly share code, notes, and snippets.

@zxh
Last active May 2, 2017 05:37
Show Gist options
  • Save zxh/027a8c6861efbe821d42b7900b8631cf to your computer and use it in GitHub Desktop.
Save zxh/027a8c6861efbe821d42b7900b8631cf to your computer and use it in GitHub Desktop.
List pattern matching last element in Scala.

Scala pattern matching 太强大了,但是想匹配一个 list 的最后一个元素,有些蛋疼。 本来想尝试 case (List(_* ,last)) => ... 但是居然编译都报错,原来 _* 只能扔到最后去。 如果用

(1 to 9).toList match {
  case _ :: 9 :: Nil=> "no way"
}

这种方式呢,发现 placeholder 代表一个元素,不能是一个list, 换成 triple colon 呢,scala 居然不能识别,醉了。 话又说回来了, a :: b 本质就是 ::(a, b) 嘛

那要怎么搞呢。提供一个思路。。自己定义匹配的方法:

object ::> {
  def unapply[A](l: List[A]) = Some((l.init, l.last))
}

然后在用的时候:

case _ ::> last if last == 3 => println("really endw with 3")

搞定了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment