How to convert the below JavaScript example to corresponding code in Java 8 with lambda. I am trying to get the Java 8 lambda.
Made up example.
// js
var isFlag = true,
name = (function () {
if (isFlag) return "A";
else return "B";
})();
console.log(name);
//outputs: A
I have tried writing it in Java 8, but the syntax or something is wrong. See the below code.
// LambdaTest.java
class LambdaTest {
public LambdaTest() {
boolean isFlag = true;
String name = () -> { //I know this is wrong. It is not an IIFE. But how to write one?
if (isFlag) return "A";
else return "B";
};
System.out.println(name);
}
public static void main(String... args) {
LambdaTest lt = new LambdaTest();
}
}
// outputs:
// LambdaTest.java:4: error: incompatible types: String is not a functional interface
// String name = () -> {
// ^
// 1 error
Thanks.
I am not java programmer but seems that something like this do the trick: