Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 594
Ming Avatar asked May 27 '19 01:05

Ming


1 Answers

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;
like image 199
Jacob G. Avatar answered Oct 06 '22 01:10

Jacob G.