#Tagged unions in Java using sealed interfaces

12 messages · Page 1 of 1 (latest)

lucid root
#

Can you actually create a covariant sealed interface in Java? I'm trying to create a tagged union using sealed interfaces and records. I can't figure out how to keep the type in a function signature that would return it though

example

public sealed interface RepoResult<T> permits RepoResult.NotFound, RepoResult.Success {

    record Success<T>(T value) implements RepoResult<T> {}
    record NotFound(String message) implements RepoResult<Void> {}
}

This is invariant so I can't return NotFound for any function declared to return RepoResult<T> e.g RepoResult<Long>. Is this possible. My initial thinking is that it's not possible because Java only has use site variance, but I'm a java noob so...

cerulean micaBOT
#

This post has been reserved for your question.

Hey @lucid root! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

misty locust
#

The generic value is a part of the signature, you could change

record NotFound(String message)

to

record NotFound<T>(T value, String message)
#

Nevermind, it's of type RepoResult<Void> I didn't read it properly

#

Well actually.

#

No, I am correct.

lucid root
#

Adding a type parameter like that will make it compile, but it's not really what I want

misty locust
#

You have 2 options

#

You could either use raw types, which would work, but I wouldn't recommend

#

Or you could also have yet another wrapper for both interfaces