Why is an exception thrown when using ?:
operator in a Java 8 lambda expression?
When I try to run the following sample code:
import java.util.ArrayList;
import java.util.List;
public class TestClass
{
public static void main(String[] args)
{
List<Foo> foos = new ArrayList<>();
boolean b = true;
foos.forEach(foo -> (b ? foo.doSth(1) : foo.doSth(2)));
}
@FunctionalInterface
interface Foo
{
public void doSth(int i);
}
}
I get the following exception:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at gui.marksDetection.view.TestClass.main(TestClass.java:8)
When replacing the lambda expression with a for-each-loop, or replacing (b ? foo.doSth(1) : foo.doSth(2))
with an if-else-block, everything works fine, so there seems to be a problem with the combination ?: + lambda
. However, Eclipse does not mark it as an error.
The Ternary statement requires the separate parts to be expressions and not statements
You are not allowed to invoke statements in the separate branches.
For more information see the Java Language specification section 15.25
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