kotlin get "Type argument is not within its bounds" for recursive bounds

Viewed 43

Get recursive "Type argument is not within its bounds" for recursive bounds when initializing an object

class RawType {
  
  inner class BoundRecursively<T : BoundRecursively<T>?>

  fun test() {
    
    val boundRecursively = BoundRecursively<BoundRecursively<Any>?>()
  }
}

the compiler gives error


Type argument is not within its bounds: should be subtype of 'RawType.BoundRecursively<TypeVariable(T)>?'
Type argument is not within its bounds: should be subtype of 'RawType.BoundRecursively<Any>?'
Type argument is not within its bounds: should be subtype of 'Any'
Type argument is not within its bounds: should be subtype of 'RawType.BoundRecursively<RawType.BoundRecursively<Any>?>?'
Type argument is not within its bounds: should be subtype of 'RawType.BoundRecursively<RawType.BoundRecursively<Any>?>?'
Type argument is not within its bounds: should be subtype of 'RawType.BoundRecursively<Any>?'

Any suggestion on how to fix the initialization

1 Answers

When you intialize an object:

val boundRecursively = BoundRecursively<BoundRecursively<Any>?>()

First of all intializing an object with itself is very dangerous. You should be careful when doing this. Second of all you need a stopping condition, otherwise BoundRecusively will intialize an infinite number of BoundRecursively objects. You need to tell it when to stop intializing BoundRecursively objects.

Related