Re: Unexpected compile error with reflective calls
Jason Zaugg <[email protected]>
| Newsgroups | gmane.comp.lang.scala |
|---|---|
| Message-ID | <CAG3_yeVWzDXcS-19q13kVUpEbBQyfwihQQg1nx9RPadT4xj9pQ@mail.gmail.com> |
On Mon, Mar 2, 2015 at 2:59 PM, Steven Heidel <[email protected]> wrote: > Take a look at the following code: > > import scala.language.reflectiveCalls > > trait A { > def sameName: Object > } > > object B extends A { > def sameName = new Object { > def method = ??? > } > > def differentName = new Object { > def method = ??? > } > > def main = { > sameName.method // doesn't compile, "value call is not a member of > Object" > differentName.method // compiles > } > } > > I expected this to compile because I'm refining both the method sameName > and differentName's Object with "method". The only difference is that > sameName implements a method in trait A whereas differentName does not. > > I'm assuming this is because type inference picks up Object for the return > type of sameName from trait A instead of its actual type Object{def method: > Nothing}. Is this a bug or a feature? > Hi Steven, This is intentional, albeit subtle. The type of the overridden method A#sameName is used as the expected type <https://github.com/scala/scala/blob/v2.11.5/src/compiler/scala/tools/nsc/typechecker/Namers.scala#L1099-L1111> when typechecking the body of B#sameName. Furthermore, when typechecking an instantiation of an anonymous class, the expected type is a signal to hide declarations from the anonymous class <https://github.com/scala/scala/blob/v2.11.5/src/compiler/scala/tools/nsc/typechecker/Typers.scala#L2309-L2353> from the expression’s type. If you don’t want to remember these rules (who would!?), annotating return types of non-private methods is your best bet. -jason -- You received this message because you are subscribed to the Google Groups "scala-language" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. For more options, visit https://groups.google.com/d/optout.