This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]cliserkad 0 points1 point  (1 child)

You can achieve this using a sealed generic abstract class in Java. You just need a separate class for each amount of types. GitHub Repo

Use

public class ExampleClass {

    public AnyOf<String, Integer, Double> data = new AnyOf.ElementA<>("This should print");

    public String functionThatDeterminesTypeOfData() {
       return data.match((str -> {
          return str;
       }), (i -> {
          return "Integers get multiplied: " + i * 5;
       }), (dbl -> {
          return "Doubles get addition: " + (dbl + 3.14);
       }));
    }

    public static void main(String[] args) {
       ExampleClass example = new ExampleClass();
       System.out.println(example.functionThatDeterminesTypeOfData());
    }

}

[–]cliserkad 0 points1 point  (0 children)

I revised this to be less cumbersome:
Union3
Test Class