2012-04-27 47 views
0

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

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,然后我想返回该变量。有任何想法吗?

回答

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的最后一个表达式。在这里,匹配的casecase namecase name区块下的最后一个表达式是name,所以这就是整个比赛评估的结果。所以功能func返回name,当我们呼叫func("test"). Thus, x is assigned to be“测试”时,它是"test"

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

+0

地狱是啊,语法仍然有点让我困惑,但你已经帮我清理了我的代码的HEAPS。 – Schroedinger 2012-04-27 04:31:23