Model a payment outcome as a sealed interface with Success, Declined and Failed records; simulate several payments and produce user messages and a summary with an exhaustive switch.
Solution
Main.java
import java.util.List;
sealed interface PaymentResult permits Success, Declined, Failed { }
record Success(String txnId, int amount) implements PaymentResult { }
record Declined(String reason) implements PaymentResult { }
record Failed(String error, boolean retryable) implements PaymentResult { }
public class Main {
static PaymentResult pay(String card, int amount) {
if (card.startsWith("0")) return new Declined("card blocked");
if (amount > 50000) return new Declined("limit exceeded");
if (card.endsWith("9")) return new Failed("gateway timeout", true);
return new Success("TXN" + (card.hashCode() & 0xFFF), amount);
}
static String message(PaymentResult r) {
return switch (r) {
case Success(var id, var amt) -> "paid Rs " + amt + " (" + id + ")";
case Declined(var why) -> "declined: " + why;
case Failed(var err, var retry) when retry -> "temporary problem (" + err + "), please retry";
case Failed(var err, var retry) -> "failed: " + err;
};
}
public static void main(String[] args) {
List<PaymentResult> results = List.of(pay("4111", 1200), pay("0111", 500), pay("4119", 800), pay("4222", 75000));
results.forEach(r -> System.out.println(message(r)));
long ok = results.stream().filter(r -> r instanceof Success).count();
int collected = results.stream().mapToInt(r -> r instanceof Success s ? s.amount() : 0).sum();
System.out.println(ok + " of " + results.size() + " succeeded, collected Rs " + collected);
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!