Is it possible to directly assign the return value of a method to a variable?

Ming :

In JavaScript, it's possible to do something along these lines:

var qwerty = (function() {
    //some code
    return returnValue;
}

This would assign returnValue to qwerty. Is there any way to do something similar in Java? Something like:

int num = {
    public int method() {
        //some code
        return val;
    }
}

I understand that I could write out a separate method, but I'd like to do it in a way similar to above as it looks neater and cleaner in the code I'm writing.

Jacob G. :

Because your function doesn't specify any parameters, you're most-likely looking for the IntSupplier functional interface:

IntSupplier supplier = () -> {
    int val = ...;
    //some code
    return val;
};

int num = supplier.getAsInt();

If you really want to inline it, then you can use the following (which is unreadable, so I wouldn't recommend it):

int num = ((IntSupplier) () -> {
    int val = ...;
    //some code
    return val;
}).getAsInt();

Because the above IntSupplier isn't stored in a variable, it's logically equivalent to the following:

int val = ...;
//some code
int num = val;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=68637&siteId=1