Optional generic type argument 可选的泛型类型参数

huangapple go评论71阅读模式
英文:

Optional generic type argument

问题

我想声明一个通用类,该类将用于三元组 - keyvaluemetadata

keyvalue 字段是必需的,但 metadata 字段是可选的。

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

在使用上述类时,我必须像下面这样初始化它 -

Triplet<Integer, String, String> t1 = new Triplet<>();
// 设置器

但是对于某些用例,metadata 是可选的。因此,当我将第三个类型参数指定为 null 时,编译器会报错 -

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

在哪种情况下,我应该正确实例化一个参数化类型,该类型适用于多种类型,其中在使用点指定的一个类型参数是可选的?

英文:

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&lt;K,V,M&gt;{
    K key;
    V value;
    M metadata;
    //setters and getters
}

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

Triplet&lt;Integer, String, String&gt; t1 = new Triplet&lt;&gt;();
// 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&lt;Integer, String, null&gt; t2 = new Triplet&lt;&gt;();

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?

答案1

得分: 9

你可以使用 Void,例如:

Triplet&lt;Integer, String, Void&gt; t2 = new Triplet&lt;&gt;();
英文:

You can use Void e.g.

Triplet&lt;Integer, String, Void&gt; t2 = new Triplet&lt;&gt;();

答案2

得分: 5

我认为,如果您确定第三个参数不存在(如使用 null 所意图的那样),那么它就不再是三元组,而是一对。只需保持简单,使用一个 Pair 类即可。

英文:

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.

答案3

得分: 5

Java不支持“optional”或渐进式类型。您可以尝试创建一个子类,将元数据默认设置为null,即NoMetadataTriple<K,V>,或者像其他答案中提到的那样将Void用于M。

Void "类型" 不能被实例化。它基本上是void(输出参数)作为一个Class

英文:

Java does not support "optional" or gradual typing. You can try creating a subclass that defaults metadata to null, i.e. NoMetadataTriple&lt;K,V&gt;, or give Void for M instead as mentioned in the other answer.

The Void "type" cannot be instantiated. It's basically void (the output parameter) as a Class.

huangapple
  • 本文由 发表于 2020年8月13日 19:06:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63393807.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定