In Java, is an expression assignable to a declared variable iff. it can be passed as a parameter declared with the same type?

て烟熏妆下的殇ゞ 提交于 2019-12-07 08:58:25

问题


This question was inspired by Java 8: Is it possible to assign a method reference to a variable?.

As I currently understand (which may not be completely right), the invocation of, say fooMethod(FooType ft) as fooMethod(myFooInstance) causes an implicit assignment of myFooInstance to a local variable within fooMethod's body, whose name is ft, and whose type is declared as FooType. Clearly, in this case, I could also assign myFooInstance to a field or local variable whose type is FooType, for instance, in a class with a declared field private FooType fooField, using this.fooField = myFooInstance;.

However, scanning JLS 8.4.1, there is no mention of assignment when dealing with method parameters. JLS 5.3 similarly does not mention assignability, at least with an initial reading of that section.

So, are rules for variable typing and use the same in both strict invocation, and assignment contexts? (or, does is a value assignable to a method parameter if and only if it is assignable to a field/local variable with the same declaration?)

(the same declaration implies a field/local/parameter that is not final, and visibility/accessibility of fields is not considered for the purposes of this question)

Edit:

FooType is not necessarily a concrete class, but a tool of phrasing my question. It could be a functional interface, plain-old-interface, proxy class, primitive, etc.

To rephrase a bit clearly, is there a value (or return value of a function call/language construct that returns a value), that can be assigned to:

FooType ft;

or passed to

myMethod(FooType ft){ ...

but not both for some choice of type for FooType (which would act as a counterexample and make the answer "no").


回答1:


You would need to compare 5.2 Assignment Conversion and 5.3 Method Invocation Conversion for differences. I can't see any that are relevant.



来源:https://stackoverflow.com/questions/25776804/in-java-is-an-expression-assignable-to-a-declared-variable-iff-it-can-be-passe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!