Quick revision
The short answer
A minimal Result<T> is a sealed interface with exactly two record implementations: Ok, which holds a value, and Err, which holds an error. Because the interface is sealed, a switch over a Result knows every possible case, so the compiler can check that both are handled, and a default map method can transform the value inside Ok while passing Err through unchanged.
What to remember
In this answer, we built a Result<T> from a sealed interface and two records, added a map method whose switch on this is exhaustive because the interface is sealed, and handled both cases at the call site with record patterns so the failure cannot be ignored. We finished by replacing the string error with a structured Failure type, so callers can branch on it safely and the compiler checks every mapping.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A minimal Result<T> is a sealed interface with exactly two record implementations: Ok, which holds a value, and Err, which holds an error. Because the interface is sealed, a switch over a Result knows every possible case, so the compiler can check that both are handled, and a default map method can transform the value inside Ok while passing Err through unchanged.
Why this question is asked
Many methods have an expected way to fail: parsing a number, finding a customer, charging a card. Throwing an exception for these hides the failure from the method signature, and callers forget to handle it. A Result type puts the failure into the return type instead. Before Java 17 we needed a library for this; now sealed interfaces, records and pattern matching give us everything in a few lines. Interviewers ask it because writing it well shows we understand all three features and how they fit together. In this answer, we will recap the language features involved, write the type step by step, add map, handle both cases with a switch, and then improve the error side so it carries structured information instead of a plain string.
1A Quick Recap of the Three Language Features
A record is a class whose only job is to carry data. When we write record Ok<T>(T value), Java generates a private final field, a constructor, an accessor method value(), and equals, hashCode and toString.
A sealed interface lists the classes that are allowed to implement it, using the permits clause. If we nest the implementations inside the interface, or put them in the same file, Java can work out the list without a permits clause. The important effect is that the compiler now knows the complete set of subtypes. No other code, in this module or any other, can add a third one.
Pattern matching for switch, final since Java 21, lets a switch test the type of a value and bind it to a variable in one step, as in case Ok<T> ok ->. When the switch covers every permitted subtype of a sealed interface, it is exhaustive, which means the compiler accepts it without a default branch and complains if we forget a case. These three features together are what people call algebraic data types.
2Writing the Result Type
We start with the smallest version that works. The error is a String for now; we will improve it at the end. Nesting the records inside the interface keeps everything in one place and lets us leave out the permits clause.
Notice that Err is also generic, even though it does not hold a T. The reason is that an Err<Integer> must be a Result<Integer>, so that a method declared to return Result<Integer> can return either kind. The two static factory methods are a convenience: callers write Result.ok(42) and never need to name the record classes.
3Adding map With an Exhaustive Switch
map is the operation that makes a Result pleasant to use. It takes a function, applies it to the value if the Result is Ok, and returns a new Result. If the Result is an Err, there is no value to transform, so it passes the error along. We can write it once, as a default method on the interface, using a switch on this.
- Call result.map(f)Switch on this: which record is it?
- Is it Ok?The sealed interface allows only Ok and ErrYesApply f to the valueNoCopy the error into a new Err<R>
- Return Result<R>Ok holds
f(value); Err holds the same error
3 steps in order. Play them, or step through them one at a time.
Errors pass through map untouched, so a chain of maps stops transforming at the first failure.
There is no default branch, and the compiler is happy, because Result is sealed and the two cases cover every possible subtype. If someone later adds a third record, say Pending, every switch over Result stops compiling until it handles Pending. That is exactly the safety we want: the compiler finds every place that needs updating.
Notice also that the Err branch builds a new Err<>(err.error()) rather than returning err itself. The reason is the type: err is an Err<T>, but the method must return a Result<R>. Creating a new record with the same error gives it the right type without an unchecked cast.
4Handling Both Cases at the Call Site
The caller eventually has to decide what to do with the outcome. A switch with record patterns does this neatly: case Ok<Integer>(var n) both checks the type and pulls the value out of the record. Because the switch is exhaustive, the caller cannot quietly forget the error case, which is the main advantage over an exception that nothing in the signature mentions.
Notice how parseAge converts the library's exception into a Result at the edge, where the failure is expected. From there on, every caller sees the failure in the type. If a caller writes a switch with only the Ok case, the code does not compile, so a failure cannot be ignored silently in the way an unchecked exception can.
5Making the Error Structured
A String is fine for a demo, but it is weak in real code. Callers cannot branch on it reliably, an HTTP layer cannot map it to a status code without parsing text, and a typo in a message breaks logic that compares strings. A better design gives the error its own small type: an enum for the kind of failure, plus a record that carries details.
Now the inner switch over the enum is also exhaustive, so adding a new error code forces every mapping to be updated. Some teams make Result generic in the error too, Result<T, E>; that is more flexible but noisier, and a single structured Failure type is usually enough. A natural next step is flatMap, which chains operations that themselves return a Result, written with the same two-case switch.
6Follow-up questions
Why not just use Optional for this?
Optional tells us that a value is missing, but not why. A Result carries the reason, such as not found or invalid input, so the caller can react differently to each one. Optional is right when absence is the only failure and needs no explanation.
What happens to existing switches if we add a third record to the sealed interface?
Every switch over Result that has no default branch stops compiling, with an error saying the switch does not cover all possible input values. That is a feature: the compiler lists every place that must decide how to treat the new case. If code compiled against the old version meets the new record at run time, the generated switch throws a MatchException.
7Conclusion
In this answer, we built a Result<T> from a sealed interface and two records, added a map method whose switch on this is exhaustive because the interface is sealed, and handled both cases at the call site with record patterns so the failure cannot be ignored. We finished by replacing the string error with a structured Failure type, so callers can branch on it safely and the compiler checks every mapping.
Open with
I would declare a sealed interface Result of T with two nested records: Ok, holding the value, and Err, holding the error. Records give me immutable data carriers with equals and toString for free, and sealing the interface means the compiler knows these are the only two cases.
Then, if they want more
Then I add a default map method that switches on this: for Ok, it applies the function and wraps the result in a new Ok; for Err, it creates a new Err with the same error so the type becomes Result of R.
The switch needs no default branch because the sealed interface makes it exhaustive, and if anyone adds a third case, every switch fails to compile until it is handled.
At the call site, the caller uses a switch with record patterns, like case Ok(var value) and case Err(var error), so the failure path is visible in the type and cannot be silently skipped the way an unchecked exception can. One improvement I would make straight away is the error type.
A plain string is hard to branch on, so I would use a small record with an enum code and a detail message, which lets an HTTP layer map codes to status codes with another exhaustive switch. I would keep exceptions for truly unexpected failures and use Result only for outcomes the caller is expected to handle.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 17, Java 21
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.stream, package documentation, java.util.function, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a minimal Result<T> type using a sealed interface and records, with map and a way...": https://scrivio-interview-library.netlify.app/java/functional-design/c413e45f80/