[英]Adding to a Set in a conditional in Scala
I've written a visitor pattern and I'm matching an overridden subclass. 我写了一个访问者模式,我匹配一个重写的子类。 I want to add the variable to the set value of the object and then return the modified object.
我想将变量添加到对象的设置值,然后返回修改后的对象。 How can I do that syntactically?
我怎么能在语法上做到这一点?
trait PropositionOrderer extends Visitor[Proposition]{
var OurSet = SortedSet[Name] _
override def variable = {
_ match {
case name => Variable(name)//SortedSet+(name).andThen(Variable(_))
}
}
}
Is there syntax to chain like a void function that adds to the SortedSet
and then wait? 是否有类似于void函数链的语法,它会添加到
SortedSet
然后等待? I can't use andThen
because I want to do two things, I want to add it to the Set
and then I want to return the variable. 我不能使用,
andThen
因为我想做两件事,我想将它添加到Set
然后我想返回变量。 Any ideas? 有任何想法吗?
I think you mean something like this: 我认为你的意思是这样的:
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"
A match
expression will evaluate to the last expression of the matching case
. match
表达式将计算为匹配case
的最后一个表达式。 Here, the case
that matches is case name
. 在这里,
case
匹配的case name
。 The last expression under the case name
block is name
, so that's what the entire match evaluates to. case name
块下的最后一个表达式是name
,因此这是整个匹配所评估的内容。 So the function func
returns name
, which is "test"
when we call func("test"). Thus,
所以函数
func
返回name
,当我们调用func("test"). Thus,
时,它是"test"
func("test"). Thus,
func("test"). Thus,
x is assigned to be
"test"`. func("test"). Thus,
x is assigned to be
“test”。
In addition, you can perform any other operations inside the case
block you want. 此外,您可以在所需的
case
块中执行任何其他操作。 Here, we are modifying ourSet
. 在这里,我们正在修改我们的
ourSet
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.