title: kotlin generics: Cannot infer type parameter
body: <p>I need a Collection in Kotlin to contain only elements implementing a given interface. </p>
  
  <p>For example: a Map containing Collection of Animals:</p>
  
  <pre><code>interface Animal { val name: String }
  data class Monkey(override val name: String): Animal
  data class Snake(override val name: String): Animal
  </code></pre>
  
  <p>From reading the documentation and blogs and SO questions, I wrote this code that uses the Generics <strong>in</strong> keyword:</p>
  
  <pre><code>class Test {
      private val data = HashMap&lt;String, ArrayList&lt;in Animal&gt;&gt;()        
      init {
          data.put("Monkeys", arrayListOf(Monkey("Kong"), Monkey("Cheetah")))
          data.put("Snakes", arrayListOf(Snake("Monthy"), Snake("Kaa")))
      }        
  }
  </code></pre>
  
  <p>Now I want to add a method in the Test class that reads the content of 'data', for example to print it to the console:</p>
  
  <pre><code>fun printAll() {
     data.forEach { collectionName: String, animals: ArrayList&lt;in Animal&gt; -&gt; 
         println(collectionName)
         animals.forEach { animal: Animal -&gt;
             println("\t$animal")
         }
      }
  }
  </code></pre>
  
  <p>If I do that, I have a compilation error:</p>
  
  <pre><code>Error:(27, 21) Kotlin: Type inference failed: Cannot infer type parameter T in inline fun &lt;T&gt; Iterable&lt;T&gt;.forEach(action: (T) -&gt; Unit): Unit
  None of the following substitutions
  receiver: Iterable&lt;Any?&gt;  arguments: ((Any?) -&gt; Unit)
  receiver: Iterable&lt;Animal&gt;  arguments: ((Animal) -&gt; Unit)
  can be applied to
  receiver: kotlin.collections.ArrayList&lt;in Animal&gt; /* = java.util.ArrayList&lt;in Animal&gt; */  arguments: ((Animal) -&gt; Unit)
  </code></pre>
  
  <p>My solution is to force my animal to a an ArrayList&lt;<strong>out</strong> Animal>:</p>
  
  <pre><code>...
  (animals as ArrayList&lt;out Animal&gt;).forEach { animal: Animal -&gt;
      println("\t$animal")
  }
  ...
  </code></pre>
  
  <p>But I'm not sure that this is the best way to write this kind of code.
  Is there a better way to tell Kotlin that I want to use sub types in generics for both producers and consumers ?</p>