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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With