为什么 apply() 不能在包对象上以简写形式使用? [英] Why apply() can not be used in shorthand form on package objects?
问题描述
在普通对象上,我可以执行以下操作:
On normal objects, I can do the following:
object A {
def apply = "!"
}
A() // "!"
但是在包对象上,这不起作用:
But on package objects, this doesn't work:
package object A {
def apply = "?"
}
A.apply // "?"
A() // compile error
// error: package A is not a value
有什么基本的限制吗?或者这只是一个实现限制,我可以通过稍微调整编译器来解决?
Is there some fundamental limitation? Or is it just an implementation limitation, which I can fix by tweaking the compiler a bit?
推荐答案
唯一可以不用申请的方法是:
The only way you can do it without apply is this:
A.`package`()
这是因为 A
不表示值或方法,并且语言规范指出对于 f()
是有效的,f
必须有一个方法类型或一个带有 apply
方法的值类型.我不知道调整"编译器来改变这一点有多容易,但我怀疑这是否值得付出努力.如果您确实想达到这样的长度,只需将您的方法添加到 Predef
中会更容易.
This is because A
does not denote a value or a method, and the language specification states that for f()
to be valid, f
has to have a method type or a value type with an apply
method. I have no idea how easily one could "tweak" the compiler to change this, but I doubt it's worth the effort. If you do want to go to such lengths, it would be easier to just add your method to Predef
.
这篇关于为什么 apply() 不能在包对象上以简写形式使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!