Why apply() can not be used in shorthand form on p

2020-03-01 17:02发布

问题:

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?

回答1:

The only way you can do it without apply is this:

A.`package`()

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.



标签: scala