[英]Lambda Expression example not working in java 8
我正在嘗試在 java 8 中學習 Lambda 表達式。我確實安裝了 eclipse 插件和 java 8 SDK,但是當我嘗試執行以下代碼時,eclipse 顯示錯誤。
(String s) -> {
s="hello";
System.out.println(s); }
它顯示“賦值的左側必須是變量”錯誤。
請幫忙。
一個 lambda 表達式(和一個方法引用)只在需要某個函數接口實例的上下文中才有意義。 否則將無法確定 lambda 是否有效(並且它也無用,因為您不對其進行任何操作)。
就像是
Consumer<String> c = (String s) -> {
s = "hello";
System.out.println(s);
}; // as a Consumer, it doesn't really make sense for you to change s
請注意,作為Consumer
,重新分配s
的值實際上沒有意義。
我知道這個答案是在提出這個問題很久之后才出現的,但可能會幫助其他人在學習 lambdas 時對我最近遇到的同樣問題感到疑惑,並且因為您的問題對於被大量呈現不佳的示例誤導的新手有效網。
您的編譯器抱怨的原因是 - 示例不完整。 理解不完整代碼的一種方法是,它只是上下文的功能部分(缺少示例),通常可以是您自己設計的接口或 Java 8 中預定義的簡單接口之一 - 例如 Function 、BiFunction、Predicate 等。此外,在 lambda {working section} 中為您的 String s 提供值“hello”在某種程度上超出了 s 變量的目的。 這是一個更完整的類似功能示例,演示了 3 個字符串變量在 lambda 表達式中的使用:
public class LambdaTest {
// define your interface
interface Use_3_Strings {
void apply(String s1, String s2, String s3);
}
// define a test method
public void lambdaTest1(String str1, String str2, String str3) {
// your lambda expression
// defining what to do inside { }
// - like a method having 3 String parameters (s1, s2, s3)
Use_3_Strings use3strings = (s1, s2, s3) -> { System.out.println("Working with 3 strings:");
System.out.println(" String 1: " + s1);
System.out.println(" String 2: " + s2);
System.out.println(" String 3: " + s3);
StringBuilder sb = new StringBuilder();
sb.append("CSV of 3 strings:\n");
sb.append(s1);
sb.append(", ");
sb.append(s2);
sb.append(", ");
sb.append(s3);
System.out.println(sb); };
// your lambda expression in action
// executing what you coded inside { } above
use3strings.apply(str1, str2, str3);
}
}
在您的 main() 方法中,然后執行:
LambdaTest lambdaTst = new LambdaTest();
lambdaTst .lambdaTest1("Hello", "beautiful", "world");
你應該得到:
Working with 3 strings:
String 1: Hello
String 2: beautiful
String 3: world
CSV of 3 strings:
Hello, beautiful, world
lambda 表達式總是期望分配一個引用。
Java 7 代碼:
有效的:
new Hahaha() {
@Override
public void howtolaugh(int number, String sound) {
System.out.println("say "+sound + number + " number of times");
}
};
爪哇 8:
無效的:
(int i, String sound) -> System.out.println("say "+sound + i + " number of times");
盡管這兩個目的相同,但第一個是內部類。 內部類具有對封閉類的默認引用。 當它們被反編譯時,會為它們生成一個不同的類文件,格式為<Enclosing_Class_Name>$<a_number>.class
或<Enclosing_Class_Name>$<a_number>.class
。 例如:TestClass$1.class。
在 lambda 表達式中不是這種情況。 它們沒有對封閉類的隱式引用,也沒有生成不同的類。 它們需要一個顯式引用作為方法參數名稱,或者左側的引用對象或返回引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.