Scala中匿名类的Java Style Lambda表达式

时间:2018-03-07 22:25:36

标签: java scala lambda

Lambda Expressions Java Tutorial中,approach 5通过转换匿名类实例化来改进approach 4

new CheckPerson() {
    public boolean test(Person p) {
        return p.getGender() == Person.Sex.MALE
            && p.getAge() >= 18
            && p.getAge() <= 25;
    }
}

(Person p) -> p.getGender() == Person.Sex.MALE
    && p.getAge() >= 18
    && p.getAge() <= 25

Scala中是否存在等效内容,以便我可以避免这样做:

new CheckPerson {
    def test(p: Person): Boolean = {
        p.getGender == Person.Sex.MALE
            && p.getAge >= 18
            && p.getAge <= 25
    }
}

1 个答案:

答案 0 :(得分:4)

val x: CheckPerson = (p: Person) => p.getGender == Person.Sex.MALE &&
                                    p.getAge >= 18 &&
                                    p.getAge <= 25