Return multiple values from a Java method: why no n-tuple objects?

前端 未结 6 1711
故里飘歌
故里飘歌 2020-11-28 08:36

Why isn\'t there a (standard, Java certified) solution, as part of the Java language itself, to return multiple values from a Java method, rather than developers having to u

6条回答
  •  爱一瞬间的悲伤
    2020-11-28 09:11

    There is a new style of pattern available, and fits in with the "all asynchronous" nature that you might see in languages such as JavaScript.

    A lot of my code looks like this nowadays :-)

    public class Class1 {
    
        public interface Callback {
           void setData(String item1, String item2);
        }
        public void getThing(Callback callback) {
            callback.setData("a", "b");
        }
    }
    
    public class Class2 {
    
        public void doWithThing(Class1 o) {
            o.getThing(new Class1.Callback() {
                public void setData(String item1, String item2) {
                    ... do something with item 1 and item 2 ...
                }
            });
        }
    
    }
    

    No new objects to create and not that many extra classes since the interface is an inner class of the object.

    This is what makes Swift so awesome. The code can look like this:

    o.getThing({ item1, item2 -> Void in
        ... do something with item 1 and item 2 ...
    });
    

    And since the only argument is the block, even this:

    o.getThing { item1, item2 -> Void in
        ... do something with item 1 and item 2 ...
    };
    

    Java needs work to make callback laden code a lot easier to read.

提交回复
热议问题