Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception when using ?: operator in Java 8 lambda expression

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.

like image 751
Sebi Avatar asked Feb 11 '23 23:02

Sebi


1 Answers

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

like image 105
Vogel612 Avatar answered Feb 15 '23 11:02

Vogel612