title: How to retrieve items from a generic list in a type safe way
body: <p>I'd like to put items in a generic container but retrieve them in a type safe manner.  The container will tag each item with a sequence number when it's added.  I tried to implement this in Kotlin but ran into problems in the <code>pens()</code> method.  Is there a way to use type information in a function argument to define the type of the return value?</p>
  
  <pre><code>import java.util.concurrent.atomic.AtomicInteger
  import kotlin.reflect.KClass
  
  interface Item
  data class Pen(val name: String) : Item
  data class Eraser(val name: String) : Item
  data class Ref&lt;out T : Item&gt; (val id: Int, val item: T)
  
  class Container&lt;T: Item&gt; {
      private val seq = AtomicInteger(0)
      private val items: MutableList&lt;Ref&lt;T&gt;&gt; = mutableListOf()
      fun add(item: T) =  items.add(Ref(seq.incrementAndGet(), item))
  
      fun filter(cls: KClass&lt;*&gt;) : List&lt;Ref&lt;T&gt;&gt; = items.filter{cls.isInstance(it.item)}.toList()
  
      // to retrieve pens in a type safe manner
      // Type mismatch required: List&lt;Ref&lt;Pen&gt;&gt; found: List&lt;Ref&lt;T&gt;&gt; 
      fun pens(): List&lt;Ref&lt;Pen&gt;&gt; = filter(Pen::class) 
  }
  
  fun main(args: Array&lt;String&gt;) {
      val container = Container&lt;Item&gt;()
      container.add(Pen("Pen-1"))
      container.add(Pen("Pen-2"))
      container.add(Eraser("Eraser-3"))
      container.add(Eraser("Eraser-4"))
      // the filter method works
      container.filter(Pen::class).forEach{println(it)}
  }
  </code></pre>