title: Kotlin sealed class - how to sort by sealed class similar to sorting by enum
body: <p>In Java we can easily sort a Collecion by enum with something like this:</p>
  <pre><code>Collections.sort(toSortEnumList, new Comparator&lt;theEnum&gt;() {
      @Override
      public int compare(theEnum o1, theEnum o2) {
          return o1.ordinal().compareTo(o2.ordinal());
      }
  });
  </code></pre>
  <p>and the <code>toSortEnumList</code> will be ordered ascending. How can I do this with a Kotlin's sealed classes? I tried sorting by the class names but that's not by enum position. There must be some way to sort by enum position:</p>
  <pre><code>sealed class GoodCountries {
      
      class Brazil : GoodCountries() {}
  
      class USA : GoodCountries() {}
      
      class Germany : GoodCountries() {}
      
      class China : GoodCountries() {}
  }
  
   // later on
      
   var toSortList = listOf&lt;GoodCountries&gt;(China(), Brazil(), USA(), Germany())
  
   Collections.sort(
       toSortList,
       { x: GoodCountries, y: GoodCountries -&gt; y::class.java.name.compareTo(x::class.java.name) }
   )
  
   Log.v(&quot;myTag&quot;, toSortList.toString())
  </code></pre>
  <p>this prints:</p>
  <blockquote>
  <p>USA, Germany, China, Brazil</p>
  </blockquote>
  <p>descending order. Not what I want. I want to sort by sealed class order (like ordinal number in Java's enum) like this:</p>
  <blockquote>
  <p>Brazil, USA, Germany, China</p>
  </blockquote>
  <p>I thought sealed classes are supposed to be better then enums but if I can't do this maybe enums have an advantage.</p>
  <p><strong>UPDATE</strong>: Thanks to Roland's help I was able to find the list of sealed classes. but now I want to sort by it: here is what I have so far:</p>
  <pre><code>Collections.sort(toSortList, object : Comparator&lt;GoodCountries&gt; {
      override fun compare(left: GoodCountries, right: GoodCountries): Int {
          return Integer.compare(
              GoodCountries::class.sealedSubclasses.indexOf(left), 
              GoodCountries::class.sealedSubclasses.indexOf(right)
          )
      }
  })
  </code></pre>
  <p>but I get the following error at <code>indexOf</code>:</p>
  <blockquote>
  <p>Type inference failed. The value of the type parameter T should be mentioned in input types (argument type, receiver type or expected type). Try to specify it explicitely.</p>
  </blockquote>