Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional generic type argument

I want to declare a generic class that will work on triplets - key, value and metadata.

The key and value fields are mandatory but the metadata field is optional.

class Triplet<K,V,M>{
    K key;
    V value;
    M metadata;
    //setters and getters
}

While using the above class I have to initialize it like below -

Triplet<Integer, String, String> t1 = new Triplet<>();
// Setters

But for some use cases metadata is optional. So when I use null as the 3rd type argument, the compiler gives an error -

Triplet<Integer, String, null> t2 = new Triplet<>();

How should I correctly instantiate a parameterized type that works for multiple types, where one of the type arguments specified at the use-site is optional?

like image 569
Rahul Vedpathak Avatar asked Aug 13 '20 11:08

Rahul Vedpathak


2 Answers

You can use Void e.g.

Triplet<Integer, String, Void> t2 = new Triplet<>();
like image 83
Murat Karagöz Avatar answered Oct 15 '22 21:10

Murat Karagöz


I would argue that if you determine that the third parameter is not present (as intended by using null), then it's no longer a triplet, but a pair. Just keep things simple and use a Pair class instead.

like image 39
M A Avatar answered Oct 15 '22 23:10

M A