Lambda表達(dá)式addThen的理解

Lambda表達(dá)式addThen的理解

先定義一個(gè)接口類(lèi)

public interface   SYInterface {
    
    int add(int a);
    
    default SYInterface addThen(SYInterface after)
    {
        return (s) -> {
            int a = add(s);
            return after.add(a);
        };
//   或者
//      return s-> {
//          return after.add(add(s));
//      };
    }

}

測(cè)試類(lèi)里面

public class SYAddThenDemo {
    public static void main(String[] args) {
        
        SYInterface s1 = a -> a + 2 ;
        SYInterface s2 = a -> a + 3 ;

        test1(a -> a + 100);
        test2(s ->  s + 16,s ->  s + 1);
        
        test1(s1);
        test2(s1,s2);
        
    }
    static void test1(SYInterface ic)
    {
        int r = ic.add(15);
        System.out.println(r);

    }
    static void test2(SYInterface s1,SYInterface s2)
    {
    // int a = s1.addThen(s2).add(15);
        SYInterface c3 =  s1.addThen(s2);
        int r1 = c3.add(15);
        System.out.println(r1);
    }

}

每次看到這段代碼我都是一臉懵逼 int a = s1.addThen(s2).add(15);,為什么它會(huì)先調(diào)用 s1add 方法,然后調(diào)用 s2add 方法。
天資愚鈍,思考了一晚上和一個(gè)上午,終于理解了,現(xiàn)在記錄下推導(dǎo)過(guò)程,以防后面再次迷糊。

先來(lái)看一段代碼

    test1(new SYInterface() {
        @Override
        public int add(int a) {
            
            return a + 15;
        }
    });

這里使用了匿名類(lèi)來(lái)實(shí)現(xiàn),沒(méi)什么問(wèn)題,當(dāng) test1 方法里面 SYInterface ic 調(diào)用 ic.add() 的時(shí)候就是調(diào)用 匿名類(lèi)里面的 add 方法。

根據(jù)規(guī)則,我們可以把匿名類(lèi)這段實(shí)現(xiàn)修改為:

    test1(a -> a + 15);
    
    其實(shí)就是
    SYInterface ic = a -> a + 15;
    test1(ic);
    然后當(dāng) ic 調(diào)用 add 的時(shí)候,其實(shí)就是 調(diào)用 a + 15;

這段具體的規(guī)則就不講了,繼續(xù)往下

上面的理解以后,我們調(diào)用接口 SYInterface 的 add 方法的時(shí)候,其實(shí)就是調(diào)用

int add(int a) {
    return a + 15
}

然后我們看下 addThen 的實(shí)現(xiàn)

    default SYInterface addThen(SYInterface after)
    {
        return (s) -> {
            int a = add(s);
            return after.add(a);
        };
//   或者
//      return s-> {
//          return after.add(add(s));
//      };
    }

是傳入一個(gè) SYInterface 參數(shù)返回一個(gè) SYInterface 的結(jié)果。
所以 偽代碼

 SYInterface s1 = a -> a + 2 ;
 SYInterface s2 = a -> a + 3 ;
 
 s1.add(5) = {
    return 5 + 2;
 }
 s2.add(5) = {
    return 5 + 3;
 }
 
 SYInterface c3 = s1.addThen(s2) = s -> {
      int a = s1.add(s);
      reurn s2.add(a);
  }  
  
  所以 c3.add(15) 等于 調(diào)用了 
  {
        //s = 15
        int a = s1.add(s);
        reurn s2.add(a);
  }

[圖片上傳失敗...(image-3052c9-1598494165480)]
Lambda.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容