Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Java8: Lambda expression not expected here

I am trying to learn Java8 and have tried following example.

I am getting a compilation error for this code. Can you please help me to resolve this issue.

public class Lambdas {
 public static void main(String[] args) {
 System.out.println("Result Of Comparision" + () -> Integer.compare("First".length(), "Second".length()));
 }
}

Answer*

Draft saved
Draft discarded
Cancel
9
  • This is wrong. In contexts where they are legal lambdas do have values. Commented May 20, 2017 at 14:59
  • @Alexey Romanov: no, lambda expression do not have values. You can convert lambda expressions to an object of an unspecified type implementing a functional interface type having a toString() implementation returning an unspecified, most likely meaningless string. Perhaps that’s what you meant. The lambda expression itself has no value. In the current Java version, it doesn’t even have a type. Commented May 22, 2017 at 13:42
  • @Holger The specification disagrees (in docs.oracle.com/javase/specs/jls/se8/html/…): "The value of a lambda expression is a reference to an instance of a class with the following properties..." Commented May 22, 2017 at 13:57
  • @Alexey Romanov: the section is only describing the "Run-Time Evaluation of Lambda Expressions" in an assignment context, but granted, that wording can indeed mislead into thinking as the instance being the value of the lambda expression and not the result of the assignment. That would require changes, if lambda expressions are supported in different contexts. Still, it’s describing a "value" whose concatenation with a String has an unspecified, meaningless result. Commented May 22, 2017 at 14:15
  • @Holger No, this section applies in all 3 contexts where lambdas are legal. "it’s describing a "value" whose concatenation with a String has an unspecified, meaningless result" In this context it doesn't describe any value, but to say OP's code is illegal because lambdas don't have values is the wrong way around: this lambda doesn't have a value because this isn't a legal context for a lambda. Commented May 22, 2017 at 14:47

lang-java

AltStyle によって変換されたページ (->オリジナル) /