Equivalent for Python's lambda functions in Java?

前端 未结 7 1454
小蘑菇
小蘑菇 2021-02-05 06:41

Can someone please tell me if there is an equivalent for Python\'s lambda functions in Java?

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-05 07:01

    Unfortunately, there are no lambdas in Java until Java 8 introduced Lambda Expressions. However, you can get almost the same effect (in a really ugly way) with anonymous classes:

    interface MyLambda {
        void theFunc(); // here we define the interface for the function
    }
    
    public class Something {
        static void execute(MyLambda l) {
            l.theFunc(); // this class just wants to use the lambda for something
        }
    }
    
    public class Test {
        static void main(String[] args) {
            Something.execute(new MyLambda() { // here we create an anonymous class
                void theFunc() {               // implementing MyLambda
                    System.out.println("Hello world!");
                }
            });
        }
    }
    

    Obviously these would have to be in separate files :(

提交回复
热议问题