java 8 - Why lambda expression are introduced in java8 -
as know, java code easy read , quite understandable introducing lambda expression makes quite complex point of view.what makes oracle think brought in java8 main attraction.
as java programmer want know why important.
consider http://docs.oracle.com/javase/tutorial/java/javaoo/lambdaexpressions.html#approach1
lambda used make extensible code in readable way.
(disclaimer, don't "know" java, i'm more comfortable in c++)
to raise functionality out of particular scope, example, checking people, , printing them if satisfy criteria, java might using objects.
public static void printpersons( list<person> roster, checkperson tester) { (person p : roster) { if (tester.test(p)) { p.printperson(); } } } interface checkperson { boolean test(person p); } class checkpersoneligibleforselectiveservice implements checkperson { public boolean test(person p) { return p.gender == person.sex.male && p.getage() >= 18 && p.getage() <= 25; } } which use like:
printpersons( roster, new checkpersoneligibleforselectiveservice()); as non-java developer, looks kinda goofy me. person important object, but, checkperson , checkpersoneligibleforselectiveservice less motivated classes, merely existing because need them to.
it feels major importance encapsulate function has checking. if can pass that, wouldn't need deal scaffolding of classes. oh, looks can lambdas!
printpersons( roster, (person p) -> p.getgender() == person.sex.male && p.getage() >= 18 && p.getage() <= 25 ); this code super readable me, though stopped coding java in java 4.
technically, argument above isn't fair, since more compactly objects so:
printpersons( roster, new checkperson() { public boolean test(person p) { return p.getgender() == person.sex.male && p.getage() >= 18 && p.getage() <= 25; } } ); but again, need create object testing? know bad interview questions deal construction of anonymous classes this, might not intuitive syntax.
but point is, if function important thing need give code, should have mechanism can give functions code. done lambdas.
Comments
Post a Comment