Scala 匹配 + 范围的问题 [英] Problem with Scala matching + scope

查看:45
本文介绍了Scala 匹配 + 范围的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码:

case class ChangeSet(field:String, from:Object, to:Object)

private var changed:List[ChangeSet] = Nil

def change(field:String, from:Object, to:Object) {
  changed.find{ case ChangeSet(field,_,_) => true } match {
    case Some(ChangeSet(field,to,_)) => // do stuff
    case Some(_) => // do stuff
    case _ => // do stuff
  }
}

给我带来麻烦的是Some(ChangeSet(field,to,_)).

它可以编译,但似乎正在发生的是 Scala 将它填充为通配符的占位符.我基于这样一个事实,即当我执行以下操作时 Some(ChangeSet(field,to,to)) 我得到错误 to is already defined as value.

It compiles but what seems to be happening is that Scala is filling it in as a placeholder for a wildcard. I base that assumption on the fact that when I do the following Some(ChangeSet(field,to,to)) I get the error to is already defined as value.

我想要的是从方法参数中创建一个带有 to 的 ChangeSet 对象.

What I wanted is to make a ChangeSet object with to from the method parameters.

这可能吗?

推荐答案

当模式匹配 Scala 将所有以小写开头的标识符解释为占位符并填充值时.要告诉 Scala 使用 to 作为来自外部作用域的常量值,您需要用反引号包围它:`to`.或者,您可以按照 Rex Kerr 的建议将 to 的名称更改为 To,但我更喜欢将变量保持小写.

When pattern matching Scala interprets all identifiers starting with lower case as placeholders and fills in values. To tell Scala to use to as a constant value from the outer scope you need to surround it with backticks: `to`. Alternatively, you could change the name of to to To as Rex Kerr suggested, but I prefer to keep my variables lowercase.

这应该有效:

def change(field:String, from:Object, to:Object) {
  changed.find{ case ChangeSet(`field`,_,_) => true } match {
    case Some(ChangeSet(`field`, `to`, _)) => // do stuff
    case Some(_) => // do stuff
    case _ => // do stuff
  }
}

这篇关于Scala 匹配 + 范围的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆