How to combine multiple Upper Bounds syntax with delegation syntax in Kotlin
Asked Answered
H

1

5

Let's say I have the following interfaces:

interface A
interface B
interface C

I want to create class with multiple upper bounds for types A and B:

class First<T>(val t: T) where T : A, T : B

I also want to use delegation for type C:

class Second(val c: C) : C by c

My question is how do I combine both in one class declaration ?

I tried this:

class Third<T>(val t: T, val c: C) where T : A, T : B, C by c // syntax error: "Expecting : before the upper bound"

And this:

class Third<T>(val t: T, val c: C) : C by c where T : A, T : B // unresolved reference where
Hypophysis answered 27/6, 2018 at 14:44 Comment(0)
T
6

The order of these two things can be figured out pretty quickly by looking at the grammar for classes, you'll see that delegation specifiers come before type constraints:

class 
  : modifiers ("class" | "interface") SimpleName
      typeParameters?
      primaryConstructor?
      (":" annotations delegationSpecifier{","})?
      typeConstraints
      (classBody? | enumClassBody)
  ;

Then it's just a matter of figuring out how to make these work in that order - it turns out that things get parsed correctly if you put the type constraints on a new line (as seen in the documentation here and there):

class Third<T>(val t: T, val c: C) : C by c
        where T : A, T : B
Triumphant answered 27/6, 2018 at 15:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.