What is the use of specifying Generic types in the method signature when they are not getting used in the method, for instance consider the below method from Kafka Materialized:
public static <K, V, S extends StateStore> Materialized<K, V, S> as(String storeName) {
Named.validate(storeName);
return new Materialized(storeName);
}
private Materialized(String storeName) {
this.storeName = storeName;
}
Here the types K,V,S are not used in the method.
Github link for materialized class
CodePudding user response:
What is the use of specifying Generic types in the method signature when they are not getting used in the method
You actually are (or should be) using them in the method:
return new Materialized(storeName);
This is a raw type. It's a transcription error from the source code you linked:
return new Materialized<>(storeName);
is a shorthand for:
return new Materialized<K, V, S>(storeName);
But anyway, type variables on the method which are only used in the return type are used after you've called the method.
For example, creating an ArrayList<T>
in a method allows you to add instances of T
to the result.
<T> List<T> myMethod() {
return new ArrayList<>();
}
// At the call site:
List<String> list = myMethod();
list.add("Hello");
In the case of Materialized
, this gives type information about the fields which are declared in terms of these type variables: Serde<K> keySerde
, Serde<V> valueSerde
and StoreSupplier<S> storeSupplier
; Kafka can then access fields/methods on these fields which do things with specific types.