Life Codecs @ NamingCrisis.net

Ruminations. Reflections. Refractions. Code.

May 3, 2017 - Software dev Kotlin

Kotlin Quick Ref: Multiple Constraints/Bounds on Type Parameters

I’ve been using Kotlin the past few weeks, mainly to write JustLogIt!.

I very nearly thought Kotlin was missing a feature that Java has: multiple bounds or constraints on a type parameter. In Java, one can do:

interface A {}
interface B {}

// constrain the type parameter T to be a subtype of both A and B
class Foo<T extends A & B> {}

A feature I occasionally find very useful. The syntax is nowhere near the same for Kotlin, and only a very small example right at the end of the Generics documentation is provided:

https://kotlinlang.org/docs/reference/generics.html

Some discussion around the syntax can be found here:

https://discuss.kotlinlang.org/t/why-the-scattered-generic-types/1917

I had a more involved use-case:

class FragmentCanRequestPermissions<out T>(val fragment: T) :
    CanRequestPermissions, FragmentCompat.OnRequestPermissionsResultCallback
    where T: Fragment, T: FragmentCompat.OnRequestPermissionsResultCallback {
  ...
}

Thus, where defining constraints occurs at the end of other declarations.

Let’s see the more general syntax for when we have multiple type parameters, each having multiple bounds/constraints:

interface A
interface B
interface C
interface D
interface E
interface F

class Meow<ABC, CDE, DE>: A, F
where 
  ABC: A, ABC: B, ABC: C,
  CDE: C, CDE: D, CDE: E,
  DE: D, DE: E
      

In fact, as you might infer, the order of bound declarations does not matter:

class RandomOrderLikeAirportRandomChecks<ABC, CDE, DE>: A, F
where 
  ABC: A, CDE: D, ABC: C,
  DE: E, CDE: C, ABC: B, CDE: E,
  DE: D

// "Random". Yeah. Right.

Yes, I am on a plane.