同樣的Lambda表達式在IntelliJ IDEA中能運行,在Android Studio中不能?

ArrayList& strings = new ArrayList&() {
{
add("1");
add("2");
add("3");
add("4");
}
};
strings.forEach(System.out::println);

同樣的代碼在IntelliJ IDEA中能運行,在Android Studio中無法運行。這是為什麼?


找不到ArrayList.forEach()說明您的Android Studio要麼版本太低,要麼沒有配置到使用Java 8。

請參考官方文檔:Use Java 8 Language Features - Android Developers

Android supports all Java 7 language features and a subset of Java 8 language features that vary by platform version. This page describes the new language features you can use, how to properly configure your project to use them, and any known issues you may encounter.

Note: When developing apps for Android, using Java 8 language features is optional. You can keep your projects source and target compatibility values set to Java 7, but you still need to compile using JDK 8.

Support for Java 8 language features requires a new compiler called Jack. Jack is supported only on Android Studio 2.1 and higher. So if you want to use Java 8 language features, you need to use Android Studio 2.1 to build your app.

If you already have Android Studio installed, make sure you update to the latest version by clicking Help &> Check for Update (on Mac, Android Studio &> Check for Updates). If you dont already have the IDE installed on your workstation, download Android Studio here.

以上


Android官方的說法是要使用Java 8 features就需要用Jack編譯,但Jack目前(2016-11)得到的支持還不夠,例如Android Data Binding和Instant Run都還不支持Jack。

實際在Android工程中一般是使用retrolambda來支持部分Java8特性,可以和現有的各種工具和平共存。

另外由於Android本身直到API level 24(即7.0)才包括Java8新增的Collection.forEach()/.stream()等等流式處理API,因此無論是使用Jack或retrolambda,題主的例子都必須使用Android 7.0的SDK編譯,target/minSdkVersion都得是至少24,也只能在Android 7.0+的設備上運行。


除了JDK/as版本外,可能需要較高的targetsdk後才能使用Java1.8的一些新特性。

請嘗試查找Android developer blog的文章,有提到過這個事項


推薦閱讀:

idea沒有錯誤出現紅色波浪線怎麼去掉?
都說JetBrains的IDE慢,到底有多慢?
如何讓Jetbrains系列IDE代碼自動排版功能的大括弧換行?

TAG:IntelliJIDEA | Lambda表達式 | AndroidStudio |