Call from Kotlin a Java generic method defined with multiple bounds, one bound is itself a generic type

4/22/2020

I am building a Kubernetes operator in Kotlin, and I try to call a generic method that is defined with multiple bounds. The method signature is the following:

<C extends Namespaceable<C> & KubernetesClient> LeaderElectorBuilder<C> leaderElector();

You can find the source code here: https://github.com/fabric8io/kubernetes-client/blob/1150135f9febfd000396c031532efe5856037043/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/KubernetesClient.java#L427-L433

The multiple bounds syntax in Java allows to define multiple constraints on a type used in a generic class or method definition. See https://www.tutorialspoint.com/java_generics/java_generics_multiple_bounds.htm

I try to call that method in Kotlin, but it fails to infer the type, and none of my definitions are accepted by the compiler.

If I do:

client.leaderElector()

Kotlin will complain that there is "Not enough information to infer type variable C".

Any explicit type is refused, typically:

client.leaderElector<KubernetesClient>()

Kotlin will complain that "Type argument is not within its bounds. Expected: Namespaceable<KubernetesClient!>! Found: KubernetesClient!"

And the opposite ("Expected: KubernetesClient! Found: Namespaceable<KubernetesClient>!") if I use Namespaceable<KubernetesClient> for the explicit type.

How to invoke this method correctly in Kotlin?

Thanks in advance!

-- Adrien Ferrand
generics
java
kotlin
kubernetes

0 Answers