... case head +: tail => ... } where head ...">

Head :: tail matching for strings

Can I do something like this with a string:

s match { case "" => ... case head +: tail => ... } 

where head is the first character and tail is the remaining string?

In the above code, the head type is Any , and I would like it to be String or Char .

+6
source share
1 answer

case h +: t means case +:(h, t) . There is a +: object using the unapply method.

unapply method +: is defined only for SeqLike and String not SeqLike .

You need a custom unapply method like this:

 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)) 
+7
source

Source: https://habr.com/ru/post/978657/


All Articles