In Scala it is possible formulate patterns based on the invididual characters of a string by treating it as a Seq[Char].
An example of this feature is mentioned in A Tour of Scala
This is the example code used there:
object RegExpTest1 extends Application { def containsScala(x: String): Boolean = { val z: Seq[Char] = x z match { case Seq('s','c','a','l','a', rest @ _*) => println('rest is '+rest) true case Seq(_*) => false } }
}
The problem I have with this is the third line of the snippet:
val z: Seq[Char] = x
Why is this sort of cast necessary? Shouldn’t a String behave like a Seq[Char] under all circumstances (which would include pattern matching)? However, without this conversion, the code snippet will not work.
Not 100% sure if this is correct, but my intuition says that without this explicit cast you would pattern match against
java.lang.String, which is not what you want.The explicit cast forces the Scala compiler to use
Predef.stringWrapperimplicit conversion; thus, as RichString extendsSeq[Char], you are able to do a pattern match as if the string were a sequence of characters.