将字符串匹配为 Seq[Char] 的模式 [英] Pattern matching a String as Seq[Char]
问题描述
在 Scala 中,可以通过将字符串视为 Seq[Char] 来根据字符串的单个字符来制定模式.
In Scala it is possible formulate patterns based on the invididual characters of a string by treating it as a Seq[Char].
这是那里使用的示例代码:
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
为什么需要这种演员表?在所有情况下(包括模式匹配),字符串不应该像 Seq[Char] 一样吗?但是,如果没有这种转换,代码片段将无法工作.
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.
推荐答案
不能 100% 确定这是否正确,但我的直觉是,如果没有这个显式转换,您将模式匹配 java.lang.String代码>,这不是您想要的.
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.
显式转换强制 Scala 编译器使用 Predef.stringWrapper
隐式转换;因此,正如 RichString 扩展了 Seq[Char]
,你可以进行模式匹配,就好像字符串是一个字符序列.
The explicit cast forces the Scala compiler to use Predef.stringWrapper
implicit conversion; thus, as RichString extends Seq[Char]
, you are able to do a pattern match as if the string were a sequence of characters.
这篇关于将字符串匹配为 Seq[Char] 的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!