Explain Codes LogoExplain Codes Logo

What is a 'SAM type' in Java?

java
lambda
functional-programming
event-listeners
Anton ShumikhinbyAnton Shumikhin·Mar 11, 2025
TLDR

A SAM type is an interface with a single abstract method (SAM). This lone warrior is at the heart of using lambda expressions and method references in Java. SAM types lay the groundwork for functional interfaces, enabling crisper, more concise coding.

Check it out:

// SAM type: A calculator that does more than just addition @FunctionalInterface interface Calculator { int calculate(int x, int y); // SAM } // Lambda expression: Ready to add numbers faster than you can say "Hey Siri!" Calculator adder = (a, b) -> a + b; System.out.println(adder.calculate(5, 3)); // Output: 8

This design pattern is particularly powerful for quick interface implementations that can be shared around like playing cards at a poker table.

SAM's spotlight

Behold, Blades of Glory! (Runnable, Callable, and their kin)

Java 8 took SAM types under its wing, empowering lambda expressions and the interfaces we cherish: Runnable, Callable, and many others. Say goodbye to verbose anonymous classes; say hello to succinct lamdas.

// Move over Usain Bolt! // This Runnable SAM is about to give a whole new meaning to "Running..." Thread thread = new Thread(() -> System.out.println("Running... faster than ever")); thread.start();

Shape shifting: SAM as the Ultimate Transformer

Lambdas are about as flexible as a yoga instructor. They can be adapted to any interface that qualifies as a SAM type. This frees up your time for the fun stuff – like creating the last app the world will ever need!

SAM's secret - the Magic behind the Curtain

SAM’s got a trick up its sleeve. Or should we say LambdaMetafactory? The LambdaMetafactory.metafactory method pulls the strings behind the scenes, facilitating the creation of lambda function handlers and using the invokedynamic bytecode instruction. This ensures even as Java evolves, your Lambdas stay fresh – just like your favorite memes!

// A look behind SAM's curtain // Have you met LambdaMetafactory? No? Well, you're about to! MethodHandles.Lookup lookup = MethodHandles.lookup(); MethodType invokedType = MethodType.methodType(Runnable.class); MethodType methodType = MethodType.methodType(void.class); CallSite site = LambdaMetafactory.metafactory(lookup, "run", invokedType, methodType, lookup.findStatic(...), methodType); Runnable r = (Runnable) site.getTarget().invokeExact(); // Voila! Welcome to the world of Lambdas

Lambdas: More than just whip-smart code

Lambdas are more than syntactic sugar; they are Java's passport to the world of functional programming. They are your ticket to cleaner code that makes sense!

Peak SAM

Presenting SAM type, the maverick of Java interfaces. As flexible as a gymnast, as adaptable as a chameleon, SAM can do it all!

| Task | With SAM | | ---- | -------- | | Call a method? | 📞☎️ | | Handle an event? | 👍✅ | | Execute some code? | 💻⌨️ | | Return a result? | 🔄⏳ |

Evidently, the SAM type is your new best friend in the world of Java programming!

Equipped to Excel

Patterns you'll spot with SAM

SAM isn't a one-trick pony. It's the jack of all trades in the world of event listeners, the lifeblood of tasks/actions in concurrent processes, and the magic wand that lets you turn verbose legacy code into concise, understandable Lambdas.

Best buddies with SAM: Best Practices

  1. @FunctionalInterface is a SAM's best friend: Always annotate SAM types with @FunctionalInterface to let the world (and the compiler) know who's boss.

  2. Brevity is SAM's second name: Method references offer a more readable alternative when a lambda is simply playing a middleman.

  3. Less is more: While lambdas can turn verbose code into a zen garden, overusing them might just confuse everyone on your team. Use wisely!