java


Why does Java 8 sometimes allow a Consumer to have a return value but not always? [duplicate]


The following Java code fails to compile:
#FunctionalInterface
private interface BiConsumer<A, B> {
void accept(A a, B b);
}
private static void takeBiConsumer(BiConsumer<String, String> bc) { }
public static void main(String[] args) {
takeBiConsumer((String s1, String s2) -> new String("hi")); // OK
takeBiConsumer((String s1, String s2) -> "hi"); // Error
}
The compiler reports:
Error:(31, 58) java: incompatible types: bad return type in lambda expression
java.lang.String cannot be converted to void
The weird thing is that the line marked "OK" compiles fine, but the line marked "Error" fails. They seem essentially identical.
Your lambda needs to be congruent with BiConsumer<String, String>. If you refer to JLS #15.27.3 (Type of a Lambda):
A lambda expression is congruent with a function type if all of the following are true:
[...]
If the function type's result is void, the lambda body is either a statement expression (§14.8) or a void-compatible block.
So the lambda must either be a statement expression or a void compatible block:
A constructor invocation is a statement expression so it compiles.
A string literal isn't a statement expression and is not void compatible (cf. the examples in 15.27.2) so it does not compile.
Basicly, new String("hi") is an executable piece of code that actually does something (it creates a new String and then returns it). The returned value can be ignored and new String("hi") can still be used in void-return lambda to create a new String.
However, "hi" is just a constant that doesn't do anything on it's own. The only reasonable thing to do with it in lambda body is to return it. But the lambda method would have to have return type String or Object, but it returns void, hence the String cannot be casted to void error.
The first case is ok because you are invoking a "special" method (a constructor) and you are no actually taking the created object. Just to make it more clear, I'll put the optional braces in your lambdas:
takeBiConsumer((String s1, String s2) -> {new String("hi");}); // OK
takeBiConsumer((String s1, String s2) -> {"hi"}); // Error
And more clear, I'll translate that to the older notation:
takeBiConsumer(new BiConsumer<String, String>(String s1, String s2) {
public void accept(String s, String s2) {
new String("hi"); // OK
}
});
takeBiConsumer(new BiConsumer<String, String>(String s1, String s2) {
public void accept(String s, String s2) {
"hi"; // Here, the compiler will attempt to add a "return"
// keyword before the "hi", but then it will fail
// with "compiler error ... bla bla ...
// java.lang.String cannot be converted to void"
}
});
In the first case you are executing a constructor, but you are NOT returning the created object, in the second case you are attempting to return a String value, but your method in your interface BiConsumer returns void, hence the compiler error.
The JLS specify that
If the function type's result is void, the lambda body is either a
statement expression (§14.8) or a void-compatible block.
Now let's see that in detail,
Since your takeBiConsumer method is of void type, the lambda receiving new String("hi") will interpret it as a block like
{
new String("hi");
}
which is valid in a void, hence the first case compile.
However, in the case where the lambda is -> "hi", a block such as
{
"hi";
}
is not valid syntax in java. Therefore the only thing to do with "hi" is to try and return it.
{
return "hi";
}
which is not valid in a void and explain the error message
incompatible types: bad return type in lambda expression
java.lang.String cannot be converted to void
For a better understanding, note that if you change the type of takeBiConsumer to a String, -> "hi" will be valid as it will simply try to directly return the string.
Note that at first I tought the error was caused by the lambda being in a wrong invocation context, so I'll share this possibility with the community :
JLS 15.27
It is a compile-time error if a lambda expression occurs in a program
in someplace other than an assignment context (§5.2), an invocation
context (§5.3), or a casting context (§5.5).
However in our case, we are in an invocation context which is correct.

Related Links

Call JPanel inside JFrame
Reading String and Integer input from text file
How to take a string parameter (will be the path name of a file) and perform File methods like exists() and setReadOnly on it?
How to create a method and use it in another class? [closed]
Why sleeping the main Thread changes behaviour of the running other Thread in Java?
A Fundamental Query about Inheritance using two classes in Java
Java use base class for inherited native method
Java method call from Synchronized block [duplicate]
JavaFx Ensemble on Raspberry pi
Hibernate HQL: pass pair values as parameters in IN clause
How to link different URLs to different items in forEach loop in JSP page? [duplicate]
what is the difference between arraylist with and without <> operator
Co-operation of servlets and async CompletableFuture operations?
Adding Process To Fragment
Jax-WS and Spring-security Conflict
Selenium RC doesn't run the test suite by BAT file

Categories

HOME
arduino-uno
google-chrome-extension
osgi
deezer
tizen
comparison
platform-builder
rsync
amortized-analysis
jsrender
ip
ios-charts
bs4
gnupg
google-cloud-spanner
zend-framework3
alignment
serilog
reactcsstransitiongroup
nas
clickonce
scriptcs
errorlevel
graphicsmagick
sox
tapestry
realex-payments-api
php-openssl
sqlcipher
poltergeist
maxmind
delicious-api
twilio-api
usbserial
geopositioning
git-merge
restlet
dartium
dynamics-crm-2013
android-browser
android-fingerprint-api
opshub
core-plot
import-from-excel
user-accounts
chain-builder
clean-architecture
ionicons
recursive-datastructures
passport-google-oauth
fody
hover-over
cloudbees
freelancer.com-api
spim
endeca-workbench
icu4j
cyclomatic-complexity
dukescript
muse
cakephp-3.1
vstest.console.exe
census
bridge.net
operator-precedence
gwidgets
gui-test-framework
codeigniter-routing
html-helper
googlemock
android-radiobutton
poller
industrial
uv-mapping
pyhdf
oam
commoncrypto
random-seed
xamlparseexception
plasma
limejs
http-unit
simba
rdoc
frameset
word-processor
site.master
asp.net-mvc-areas
sproutcore-2
revisions
modelstate
mirah
ext3
firefox4
procedural-music
putchar
private-members

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App