函數(shù)式接口
函數(shù)式接口是指接口中只有一個需要實(shí)現(xiàn)的方法陈肛。
例如Runnable接口:
public interface Runnable {
/**
* Starts executing the active part of the class' code. This method is
* called when a thread is started that has been created with a class which
* implements {@code Runnable}.
*/
public void run();
}
Lambda 表達(dá)式
基本格式: (形式參數(shù)) ->{方法體}
如果要創(chuàng)建上面的Runnable實(shí)例米间,我們以前的寫法是:
Runnable r = new Runnable(){
public void run(){
System.out.println("線程開始");
}
}
使用Lambda寫法:
Runnable r = () -> { System.out.println("線程開始"); }
從上面可以看出挺邀,可以使用 Lambda 表達(dá)式創(chuàng)建一個 Runnable 對象界睁。
作用:對于一個函數(shù)式接口骆姐,使用Lambda表達(dá)式可創(chuàng)建該接口的對象译仗。
問題來了拼弃,為什么使用Lambda格式也能創(chuàng)建一個對象呢搀矫?
因?yàn)長ambda作用的對象是函數(shù)式接口抹沪,而函數(shù)式接口中只定義了一個抽象方法,所以創(chuàng)建該對象只需實(shí)現(xiàn)該方法即可瓤球,要實(shí)現(xiàn)的方法也就可以唯一確定下來融欧,我們只需傳入該方法所需的參數(shù)以及實(shí)現(xiàn),系統(tǒng)就能自動為我們創(chuàng)建該接口對象了卦羡。
形式參數(shù)格式
- 形式參數(shù)可已有0個或多個噪馏,使用圓括號包裹麦到,如果有多個使用逗號隔開 (arg1 , arg2 , arg3 ...)
- 形式參數(shù)可以聲明類型,也可不聲明 欠肾。例如:(String arg1 , String arg2 ...) 等價于 (arg1 , arg2 ...)
- 如果只有一個參數(shù)瓶颠,可省略 圓括號。例如:(arg1) ->{ } 等價于 arg1 ->{ }
方法體格式
- 方法體是包含在一對花括號里面
- 如果方法體只有一句刺桃,花括號可省略粹淋。例如 :
Runnable r = () -> { System.out.println("線程開始"); }
Runnable r = () -> System.out.println("線程開始");
- 如果該方法有返回值,在方法體需要返回對應(yīng)的返回值瑟慈。
自定義函數(shù)式接口
public interface MyInterface {
public void getId(int id); //該接口中只有一個需要實(shí)現(xiàn)的方法
}
//使用Lambda創(chuàng)建該接口的對象
MyInterface interface = (id) ->{ System.out.println("id:"+id) }
在Android Studio 中配置使用Lambda表達(dá)式
1. 搭建環(huán)境
版本:Android Studio 2.1 + jdk 1.8
查看當(dāng)前使用的版本:點(diǎn)擊 **Help -> About **
出現(xiàn)如下界面:
如需升級Android Studio桃移,參考:http://www.reibang.com/p/465b0234142b
2. 配置Gradle文件
如果環(huán)境搭建好,下面通過配置你app模塊下的gradle文件:
android{
...
defaultConfig{
...
jackOptions{
enabled true
}
...
}
compileOptions{
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
...
}