Covariance and generic constraints in Kotlin


#1

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]) {
  def add[U >: T](item: U) = new Stock[U](item :: contents)
  def getAll(): Iterable[T] = contents
}

Is the following Kotlin code supposed to be allowed?

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

  fun add<U>(item: U) where U : T {
  contents.add(item)
  }
}

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) doesn’t cover the usage of generic constraints.


#2

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:

``

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

This code

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

  fun add<U>(item: U) where U : T {
  contents.add(item)
  }
}


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