Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is std::variant in Java

Tags:

java

I am wondering what the closest thing to std::variant would be. I know Object exists, but that's not an option for me, I want to be able to restrict what I am dealing with.

An example of what I want to achieve with it is

static String helper(Object o) {
    switch (o.getClass().getSimpleName()) {
        case "String": 
            return String.format("String %s", o); 
        case "Integer": 
            return String.format("Integer %d", o); 
        default: 
            return String.format("Object %s", o);
    }
}

But as mentioned, I would like to be able to restrict what the input might be.

like image 604
asdasdasdadw Avatar asked Jun 15 '26 23:06

asdasdasdadw


1 Answers

Here is one example of Variant-like class which I used:

class UnionArray {
    public UnionArray(final double[] sDbl) {
        this.sDbl = sDbl;
        this.sVar = null;
    }
    public UnionArray(final VarDbl[] sVar) {
        this.sDbl = null;
        this.sVar = sVar;
    }
    final double[] sDbl;
    final VarDbl[] sVar;
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!