为什么这个Option要转换成String? [斯卡拉]
我仍然是 Scala 新手,这让我感到困惑:
import java.util.regex._
object NumberMatcher {
def apply(x:String):Boolean = {
val pat = Pattern.compile("\\d+")
val matcher = pat.matcher(x)
return matcher.find
}
def unapply(x:String):Option[String] = {
val pat = Pattern.compile("\\d+")
val matcher = pat.matcher(x)
if(matcher.find) {
return Some(matcher.group())
}
None
}
}
object x {
def main(args : Array[String]) : Unit = {
val strings = List("geo12","neo493","leo")
for(val string <- strings) {
string match {
case NumberMatcher(group) => println(group)
case _ => println ("no")
}
}
}
}
我想为包含数字的字符串添加模式匹配(这样我可以了解有关模式匹配的更多信息),并且在 unapply
中我决定返回 <代码>选项[字符串]。但是,在 NumberMatcher 情况下的 println 中,group
被视为字符串,而不是Option
。你能透露一些情况吗?运行时产生的输出是:
12,493,no
I'm still a Scala noob, and this confuses me:
import java.util.regex._
object NumberMatcher {
def apply(x:String):Boolean = {
val pat = Pattern.compile("\\d+")
val matcher = pat.matcher(x)
return matcher.find
}
def unapply(x:String):Option[String] = {
val pat = Pattern.compile("\\d+")
val matcher = pat.matcher(x)
if(matcher.find) {
return Some(matcher.group())
}
None
}
}
object x {
def main(args : Array[String]) : Unit = {
val strings = List("geo12","neo493","leo")
for(val string <- strings) {
string match {
case NumberMatcher(group) => println(group)
case _ => println ("no")
}
}
}
}
I wanted to add pattern matching for strings containing digits ( so I can learn more about pattern matching ), and in unapply
I decided to return a Option[String]
. However, in the println in the NumberMatcher case, group
is seen as a String and not as an Option
. Can you shed some light? The output produced when this is ran is:
12,493,no
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看一下此示例。
如果
unapply
方法成功提取一个值,则返回Some value
,否则返回None
。因此,在内部调用
unapply
并查看它是否返回某个值。如果是这样,我们已经得到了 true 结果,因此没有Option
类型保留。模式匹配从选项中提取返回值。Take a look at this example.
The
unapply
method returnsSome value
if it succeeded in extracting one, otherwiseNone
. So internally theinvokes
unapply
and looks whether it returns some value. If it does, we already have to true result and therefore noOption
type remains. The pattern matching extracts the returned value from the option.