title: Filter for generic type without reflection or casting
body: <p>In Kotlin there is a limited form of <a href="https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters" rel="nofollow noreferrer">reified generics</a>. Is there any way to use reification to filter for a generic type without using <code>getClass()</code> or <code>as</code> or any kind of weird annotation, ie. just by using the <code>is</code> keyword? For example, I have the following structure:</p>
  
  <pre><code>import java.util.*
  
  internal class Layout&lt;out T : LayoutProtocol&gt;(val t: T) {
      fun getName(): String {
          return t.getName()
      }
  }
  
  interface LayoutProtocol {
      fun getName(): String
  }
  
  internal class Vertical : LayoutProtocol {
      override fun getName(): String {
          return "Vertical"
      }
  }
  
  internal class Horizontal : LayoutProtocol {
      override fun getName(): String {
          return "Horizontal"
      }
  }
  
  fun main(args: Array&lt;String&gt;) {
      val layouts = LinkedList&lt;Layout&lt;*&gt;&gt;()
      layouts.add(Layout&lt;Horizontal&gt;(Horizontal()))
      layouts.add(Layout&lt;Vertical&gt;(Vertical()))
      println("Horizontal layouts:")
      layouts.filterIsInstance&lt;Layout&lt;Horizontal&gt;&gt;().forEach { println(it.getName()) }
  }
  </code></pre>
  
  <p>This outputs:</p>
  
  <pre><code>Horizontal layouts:
  Horizontal
  Vertical
  </code></pre>
  
  <p>I would like it to output the following. Is there any way to get:</p>
  
  <pre><code>Horizontal layouts:
  Horizontal
  </code></pre>
  
  <p>If we look at the source code for <code>filterIsInstance(...)</code>, Kotlin does some tricky stuff to circumvent type erasure, but still does not work:</p>
  
  <pre><code>/**
   * Returns a list containing all elements that are instances of specified type parameter R.
   */
  public inline fun &lt;reified R&gt; Iterable&lt;*&gt;.filterIsInstance(): List&lt;@kotlin.internal.NoInfer R&gt; {
      return filterIsInstanceTo(ArrayList&lt;R&gt;())
  }
  
  /**
   * Appends all elements that are instances of specified type parameter R to the given [destination].
   */
  public inline fun &lt;reified R, C : MutableCollection&lt;in R&gt;&gt; Iterable&lt;*&gt;.filterIsInstanceTo(destination: C): C {
      for (element in this) if (element is R) destination.add(element)
      return destination
  }
  </code></pre>
  
  <p>If this is not possible in Kotlin, is there any language (JVM or non-JVM) that lets me do something like the following: </p>
  
  <pre><code>inline fun &lt;reified R: LayoutProtocol&gt; filterVerticals(from: Iterable&lt;Layout&lt;R&gt;&gt;): Iterable&lt;Layout&lt;Vertical&gt;&gt; {
      val dest = ArrayList&lt;Layout&lt;Vertical&gt;&gt;()
  
      for (element in from)
          if (element is Layout&lt;Vertical&gt;)
              dest.add(element)
  
      return dest
  }
  </code></pre>