# Covariance and generic constraints in Kotlin

**URL:** https://discuss.kotlinlang.org/t/covariance-and-generic-constraints-in-kotlin/878
**Category:** Uncategorized
**Created:** [March 26, 2013, 7:25am UTC](https://discuss.kotlinlang.org/t/covariance-and-generic-constraints-in-kotlin/878 "2013-03-26T07:25:16Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![anon212](https://avatars.discourse-cdn.com/v4/letter/a/9f8e36/32.png) [@anon212](https://discuss.kotlinlang.org/u/anon212)
#### Post date: [March 26, 2013, 7:25am UTC](https://discuss.kotlinlang.org/t/covariance-and-generic-constraints-in-kotlin/878/1 "2013-03-26T07:25:16Z")

</div>

Since the check for variance positions of generic types hasn't been implemented yet, I'm having hard time to figure out the Kotlin code equivalent to following Scala code:

class Stock[+T](private val contents: List[T]) {  
&nbsp;&nbsp;def add[U &gt;: T](item: U) = new Stock[U](item :: contents)  
&nbsp;&nbsp;def getAll(): Iterable[T] = contents  
}

Is the following Kotlin code supposed to be allowed?

class Stock\<out T\> {  
&nbsp;&nbsp;var contents = java.util.ArrayList\<T\>()

&nbsp;&nbsp;fun add\<U\>(item: U) where U : T {  
&nbsp;&nbsp;contents.add(item)  
&nbsp;&nbsp;}  
}

So could I make a covariant mutable collection? If not, can I still use a constraint “where T : U” like in Scala to return a new immutable collection of type U?

The bug report ([http://youtrack.jetbrains.com/issue/KT-252](http://youtrack.jetbrains.com/issue/KT-252)) doesn’t cover the usage of generic constraints.

---

<div class="post-metadata">

### Author: ![abreslav](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/abreslav/32/8279_2.png) [@abreslav](https://discuss.kotlinlang.org/u/abreslav)
#### Post date: [March 26, 2013, 7:59am UTC](https://discuss.kotlinlang.org/t/covariance-and-generic-constraints-in-kotlin/878/2 "2013-03-26T07:59:13Z")

</div>

You want to use a lower bound in your add() function. This is not supported by Kotlin as for now. It seems that you might not need it for your use case. Just use an extension function:

``

```kotlin
fun <T> Stock<T>.add(item: T) = new Stock(…)
```

This code

> class Stock\<out T\> { &nbsp;&nbsp;var contents = java.util.ArrayList\<T\>()
> 
> &nbsp;&nbsp;fun add\<U\>(item: U) where U : T {  
> &nbsp;&nbsp;contents.add(item)  
> &nbsp;&nbsp;}  
> }

  
should not compile, because T is in a contravariant position here.

---

<div class="post-metadata">

### Author: ![mcoolive](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/mcoolive/32/6287_2.png) [@mcoolive](https://discuss.kotlinlang.org/u/mcoolive)
#### Post date: [April 25, 2019, 12:44pm UTC](https://discuss.kotlinlang.org/t/covariance-and-generic-constraints-in-kotlin/878/3 "2019-04-25T12:44:36Z")

</div>

Hi,

Is there any plan to support lower bound in next future?
