How can you extend Java to introduce passing by reference?

前端 未结 10 2257
天命终不由人
天命终不由人 2020-12-24 06:19

Java is pass-by-value. How could you modify the language to introduce passing by reference (or some equivalent behavior)?

Take for example something like

<         


        
10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-24 07:23

    To answer your question:

    Where can this fail?

    1. Final variables and enum constants
    2. 'Special' references such as this
    3. References that are returned from method calls, or constructed inline using new
    4. Literals (Strings, integers, etc.)

    ...and possibly others. Basically, your ref keyword must only be usable if the parameter source is a non-final field or local variable. Any other source should generate a compilation error when used with ref.

    An example of (1):

    final String s = "final";
    passByReference(ref s);  // Should not be possible
    

    An example of (2):

    passByReference(ref this);  // Definitely impossible
    

    An example of (3):

    passByReference(ref toString());  // Definitely impossible
    passByReference(ref new String("foo"));  // Definitely impossible
    

    An example of (4):

    passByReference(ref "literal");  // Definitely impossible
    

    And then there are assignment expressions, which seem to me like something of a judgement call:

    String s;
    passByReference(ref (s="initial"));  // Possible, but does it make sense?
    

    It's also a little strange that your syntax requires the ref keyword for both the method definition and the method invocation. I think the method definition would be sufficient.

提交回复
热议问题