我可以在Scala中定义“方法专用”字段吗? [英] Can I define “method-private” fields in Scala?
问题描述
鉴于这种情况:
object ResourceManager {
private var inited = false
def init(config: Config) {
if (inited)
throw new IllegalStateException
// do initialization
inited = true
}
}
有什么办法可以使 inited
以某种方式专用于init(),这样我可以确定此类中没有其他方法可以设置 inited = false
?
Is there any way that I could make inited
somehow "private to init()", such that I can be sure that no other method in this class will ever be able to set inited = false
?
推荐答案
来自在Scala中,如何在函数内部声明静态数据?。不要使用方法而是函数对象:
Taken from In Scala, how would you declare static data inside a function?. Don’t use a method but a function object:
val init = { // or lazy val
var inited = false
(config: Config) => {
if (inited)
throw new IllegalStateException
inited = true
}
}
在初始化外部范围(在 val
的情况下)或首次访问( lazy val
),则变量的主体将被执行。因此,已初始化
被设置为 false
。最后一个表达式是一个匿名函数,然后将其分配给 init
。然后,每次对 init
的进一步访问都会执行此匿名函数。
During initialisation of the outer scope (in case of val
) or first access (lazy val
), the body of the variable is executed. Thus, inited
is set to false
. The last expression is an anonymous function which is then assigned to init
. Every further access to init
will then execute this anonymous function.
请注意,它的行为与不完全相同之类的方法。即不带参数调用它是完全有效的。然后,它的行为就像带下划线 method _
的方法一样,这意味着它将只返回匿名函数而不会抱怨。
Note that it does not behave exactly like a method. I.e. it is perfectly valid to call it without arguments. It will then behave like a method with trailing underscore method _
, which means that it will just return the anonymous function without complaining.
如果出于某种原因您确实需要方法行为,则可以将其设为 priv val _init = ...
并从public <$ c调用它$ c> def init(config:Config)= _init(config)。
If for some reason or another, you actually need method behaviour, you could make it a private val _init = ...
and call it from public def init(config: Config) = _init(config)
.
这篇关于我可以在Scala中定义“方法专用”字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!