Java接口和Lambda函数

Java接口和Lambda函数

import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) throws Exception {
        // 修饰代表: 只有一个抽象方法
        @FunctionalInterface
        interface Power {
            // 先声明
            int template(int a, int b);
        }
        // 后定义
        Power pow = (int numBot, int numTop) -> {
            int result = 1;
            if (numTop < 0) {
                return -1;
            }

            while (numTop-- != 0) {
                result *= numBot;
            }

            return result;
        };

        /*
         * 实际上:
         * Power pow = new Power() {
         * 
         * @Override
         * public int template(int numBot, int numTop) {
         * 
         * int result = 1;
         * if (numTop < 0) {
         * return -1;
         * }
         * 
         * while (numTop-- != 0) {
         * result *= numBot;
         * }
         * 
         * return result;
         * 
         * }
         * };
         */

        // 这里其实就是继承和多态重写的方法,后期调用需要 pow.template(), 真的好别扭.
        // Java 包袱太沉重了,啥啥要用类包装,太执念了.

        /*
         * Similarly in CPP:
         * 
         * std::function<int(int, int)> mypowFunc;
         * mypowFunc = [](int numBot, int numTop){
         * . . .
         * 
         * return result;
         * }
         * 
         */

        System.out.print("Type a numBot: ");
        Scanner sc = new Scanner(System.in);
        int numBot = sc.nextInt();
        System.out.print("Type a numTop: ");
        int numTop = sc.nextInt();
        sc.close();

        System.out.printf("\n%d's to %dth power is %d.", numBot, numTop, pow.template(numBot, numTop));

    }
}

真笑了,Java越学越别扭,前人亦有吐槽,这里刨根问底问了下豆包的回答,发现原来Java也是积病重重.

使用社交账号登录

  • Loading...
  • Loading...
  • Loading...
  • Loading...
  • Loading...