Code Monkey home page Code Monkey logo

lambdavsmethodref's Introduction

Companion blog post on Memerocket: Use Java Lambdas Instead of Method Refs Sometimes

When map()ing via Java streams or Optional, it's often convenient to use method references:

interface Speaker {
    String speak();
}

class AdmiralStockdale implements Speaker {
    public String speak() {return "gridlock!";}
}

final Optional<Speaker> speaker = Optional.of(new AdmiralStockdale());

System.out.println(speaker.map(Speaker::speak).get());

=> "gridlock!"

But because a method reference always includes a class (or interface) name this sometimes seems needlessly verbose. (Speaker::speak). It's not only verbose—it's worse than that. It mentions the class (interface) name. This often forces the developer to go look up that name. Later, that name must be maintained.

An alternative is to use lambda:

System.out.println(speaker.map(s->s.speak()).get());

=> "gridlock!"

At the point where we send the speak() message, we don't assume anything about the type of a—only that it can speak().

The compiler takes care of figuring out if s (speaker) can speak(). Later, if the class names, or class/interface hierarchy change, our mapping code is stable. As with a method reference, our type checker ensures compatibility.

Don't repeat yourself!

lambdavsmethodref's People

Contributors

bill avatar

Watchers

 avatar James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.