head ::用于字符串的尾部模式匹配

Ily*_*gan 8 scala pattern-matching

我可以用字符串做这样的事情:

s match {
  case "" => ...
  case head +: tail => ...
}
Run Code Online (Sandbox Code Playgroud)

head第一个字符在哪里,tail是剩下的字符串?

在上面的代码中,类型headAny,我希望它是StringChar.

sen*_*nia 7

case h +: t手段case +:(h, t).有对象+:unapply方法.

unapply对象的方法+:仅定义为SeqLikeString不定义SeqLike.

你需要一个unapply像这样的自定义方法:

object s_+: {
  def unapply(s: String): Option[(Char, String)] = s.headOption.map{ (_, s.tail) }
}

"abc" match {
  case h s_+: t => Some((h, t))
  case _ => None
}
// Option[(Char, String)] = Some((a,bc))
Run Code Online (Sandbox Code Playgroud)