在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
}
}
答案 0 :(得分:4)
val x: CheckPerson = (p: Person) => p.getGender == Person.Sex.MALE &&
p.getAge >= 18 &&
p.getAge <= 25