TransWikia.com

Lambda expresions and "? :" operator in Java 14

Stack Overflow Asked by ThePrettyFace on December 28, 2020

Good day to everyone,

I have a question regarding the usage of the ? : operator in the lambda expressions, especially in the switch statements. Could you kindly clarify, why the below code would not work and will be marked as Not a statement

 switch (separatedTransaction[0]) {
            case "u" -> processUpdate(Integer.parseInt(separatedTransaction[1]), Integer.parseInt(separatedTransaction[2]), separatedTransaction[3]);
            case "o" -> processOrder(separatedTransaction[1], Integer.parseInt(separatedTransaction[2]));
            case "q" -> separatedTransaction.length > 2 ? processQuery(Integer.parseInt(separatedTransaction[2])):processQuery(separatedTransaction[1]);
            default -> System.out.println("Invalid transaction");
        }

And the next one will.

 switch (separatedTransaction[0]) {
            case "u" -> processUpdate(Integer.parseInt(separatedTransaction[1]), Integer.parseInt(separatedTransaction[2]), separatedTransaction[3]);
            case "o" -> processOrder(separatedTransaction[1], Integer.parseInt(separatedTransaction[2]));
            case "q" -> {
                if (separatedTransaction.length > 2) {
                    processQuery(Integer.parseInt(separatedTransaction[2]));
                } else {
                    processQuery(separatedTransaction[1]);
                }
            }
            default -> System.out.println("Invalid transaction");
        }

Is there a way to use the ? : operator in the lambda expressions at all?
If so, could you kindly provide some code examples.

One Answer

Forget about all the jazz of that switch statement, it's a red herring; completely irrelevant to the situation (and as a side note, those -> arrows aren't 'lambdas'. They're just part of switch-as-expression syntax).

Just this:

separatedTransaction.length > 2 ? processQuery(Integer.parseInt(separatedTransaction[2])):processQuery(separatedTransaction[1])

explains the failure. That is invalid java code. And wrapping it in a new feature introduced in java14 isn't going to make it any more legal.

The ternary operator construct takes the following form:

booleanExpression ? expr1 : expr2

where expr1 and expr2 must themselves be expressions. The type of the whole thing is the common ground between the type of expr1 and expr2, and, crucially, that common ground must not be void.

That's the problem: processQuery returns void and therefore cannot be used in any of the 3 'slots' in a ternary expression.

Correct answer by rzwitserloot on December 28, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP