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 type of head is Any, and I would like it to be String or Char.
case h +: t means case +:(h, t). There is object +: with unapply method.
Method unapply of object +: is defined only for SeqLike and String is 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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With