Java Variant Type

CK CK 3788 
Created at  
213 0 0

Overview of Variant Types in Java

In type theory, a Variant Type (also known as a Sum Type, Tagged Union, or Discriminated Union) represents a data structure that can hold a value of one of several distinct, pre-defined types at any given time.

 

Unlike languages such as Rust (enum) or C++ (std::variant), Java historically lacked a native construct for variant types. However, starting with Java 17, Java natively supports variant types through the combination of three features:

  • Sealed Classes/Interfaces: Restrict which sub-types can extend or implement them.
  • Records: Provide concise, immutable data carriers.
  • Pattern Matching for Switch (standardized in Java 21): Enables exhaustive type-safe branching without manual casting.

 

 

Defining a Variant Type in Java

To model a variant type, a sealed interface acts as the base type, and record implementations define the specific variations allowed.

 

 

Example: Payment Method Variant

Below is a definition of a PaymentMethod variant type that can only be a CreditCard, PayPal, or Crypto.

// Base Variant Interface
public sealed interface PaymentMethod permits CreditCard, PayPal, Crypto {}

// Concrete Variants
public record CreditCard(String cardNumber, String expiryDate, int cvv) implements PaymentMethod {}

public record PayPal(String email) implements PaymentMethod {}

public record Crypto(String walletAddress, String network) implements PaymentMethod {}

 

 

Function Based on the Java Variant Type

Because the base interface is sealed, the compiler enforces exhaustive checking when using a switch expression. This means no default clause is needed if all variants are handled.

 

 

Function Implementation

public class PaymentProcessor {

    public static String processPayment(PaymentMethod method, double amount) {
        // Pattern matching switch handles each variant type specifically
        return switch (method) {
            case CreditCard card -> String.format(
                "Charged $%.2f to Credit Card ending in %s.", 
                amount, 
                card.cardNumber().substring(card.cardNumber().length() - 4)
            );
            
            case PayPal paypal -> String.format(
                "Charged $%.2f to PayPal account (%s).", 
                amount, 
                paypal.email()
            );
            
            case Crypto crypto -> String.format(
                "Transferred $%.2f equivalent via %s to address %s.", 
                amount, 
                crypto.network(), 
                crypto.walletAddress()
            );
        };
    }

    public static void main(String[] args) {
        PaymentMethod card = new CreditCard("1234567890123456", "12/26", 123);
        PaymentMethod paypal = new PayPal("user@example.com");
        PaymentMethod crypto = new Crypto("0x123abc456def", "Ethereum");

        System.out.println(processPayment(card, 150.00));
        System.out.println(processPayment(paypal, 45.50));
        System.out.println(processPayment(crypto, 1200.00));
    }
}

 

 

Key Advantages of Modern Java Variants

  • Type Safety: Eliminates generic Object references and manual instanceof casts.
  • Compile-Time Exhaustiveness: If a new subtype (e.g., BankTransfer) is added to PaymentMethod, the compiler throws an error on the switch statement until the new case is handled.
  • Immutability: Using record guarantees that variant data is read-only and thread-safe.
Tags Discriminated Union Java Java 21 Features Java Programming Java Records Java Variant Type Pattern Matching Sealed Classes Sum Types Java Switch Expression Type Safety Facebook X
Comments 0
Similar posts
  1. Your Comprehensive Guide to Flink & Kafka for Real-time Stream Processing
    422
  2. Java Kafka on CentOS 7: Install, Configure, & Run with Examples
    430
  3. How to download/grap web pages or XML document at internet website in Delphi XE?
    880
  1. Beyond venv: Java's Project Isolation Strategy
    486
  2. Simple Java Code to display Hello, World on the web
    569
  3. Why Java Spring Framework is Considered Optimized for Docker
    1,032
  4. Spring Framework: Evolution, Trends, and Architectural Innovation
    1,275
  5. What Replaced JSP? Modern Java Web Dev Explained (with Examples)
    267
  6. Java Maps: HashMap vs. LinkedHashMap vs. TreeMap Explained
    234
  7. How to resize image ?
    1,314
  8. How to set and get sessions on JSP code ?
    1,041
  9. How to add a declaration on JSP code ?
    1,128
  10. How to include file in JSP ?
    1,256
  11. How to print out text strings on HTML directly ?
    909
  12. Clipboard copy function working
    3,382
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,245
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    104
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    107
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    208
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    153
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    116
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    598
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    230
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233