在 Android Studio 中使用 Lambda 表达式的两种方法

方法一:RetroLambda

  1. 在项目根目录下的 build.gradle 中加入
classpath 'me.tatarka:gradle-retrolambda:3.6.0'
  1. 在 module 目录下的 build.gradle 中使用插件,加入
apply plugin: 'me.tatarka.retrolambda'
  1. 在 module 目录下的 buidle.gradle 的 android 中加入
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
  1. 最终结果
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        ...
        classpath 'me.tatarka:gradle-retrolambda:3.6.0'
    }
}
apply plugin: 'me.tatarka.retrolambda'
...
android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

方法二:Jack

  1. 在 module 目录下的 buidle.gradle 的 defaultConfig 中加入
jackOptions {
      enabled true
}
  1. 在 module 目录下的 buidle.gradle 的 android 中加入
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
  1. 最后结果
android {
    ...
    defaultConfig {
        jackOptions {
            enabled true
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

比较

目前来说 Jack 是 Google 官方给出的支持Java 8特性的方法,但是编译速度很慢非常慢,且暂不支持Instant Run

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容