0

我已经编写了一个访问者模式,并且正在匹配一个被覆盖的子类。我想将变量添加到对象的设置值中,然后返回修改后的对象。我怎样才能在语法上做到这一点?

trait PropositionOrderer extends Visitor[Proposition]{
  var OurSet = SortedSet[Name] _
    override def variable = {
      _ match {
        case name => Variable(name)//SortedSet+(name).andThen(Variable(_))
      }
    }
}

是否有语法可以像添加到SortedSet然后等待的 void 函数一样链接?我不能使用andThen,因为我想做两件事,我想将它添加到Set然后我想返回变量。有任何想法吗?

4

1 回答 1

2

我想你的意思是这样的:

var ourSet = Set[String]()
def func(s: String) = 
  s match {
    case name =>        // a `case` can be followed by multiple statements 
      ourSet += name    // first we add `name` to the set
      name              // the last expression gets passed up to the assignment of x
  }
val x = func("test")
// ourSet is now Set("test")
// x is now "test"

match表达式将计算为匹配的最后一个表达式case。在这里,case匹配的是case namecase name块下的最后一个表达式是name,所以这就是整个匹配的结果。所以函数func返回name,也就是"test"我们调用func("test"). Thus,x is assigned to be"test"` 的时候。

此外,您可以在case您想要的块内执行任何其他操作。在这里,我们正在修改ourSet.

于 2012-04-27T03:45:08.050 回答