title: Retrofit 2 response body to custom class
body: <p>Currently, I use <a href="http://square.github.io/retrofit/" rel="nofollow noreferrer">retrofit2</a> to call restful apis and get response. Because the response body can be multiple types, I wrote the code following.</p>
  
  <pre><code>//Interface
  @FormUrlEncoded
  @POST("payments/events/{id}")
  fun postPayment(@Path("id") id: String): Call&lt;Any&gt;
  
  //Api Manager
  fun postPayment(id: String): Observable&lt;Any&gt; {
      return Observable.create {
          subscriber -&gt;
          val callResponse = api.postPayment(id)
          val response = callResponse.execute()
  
          if (response.isSuccessful) {
              if (response.body() is MyClass1) {
                  // never success... 
              } else if (response.body() is MyClass2) {
                  // never success...
              }
              subscriber.onNext(response.body())
              subscriber.onCompleted()
          } else {
              subscriber.onError(Throwable(response.message()))
          }
      }
  }
  </code></pre>
  
  <p>So I'm not able to cast <code>response.body()</code> to <code>MyClass1</code> or <code>MyClass2</code>.
  <code>response.body() as MyClass1</code> occurs error too.</p>
  
  <p><code>MyClass1</code> and <code>MyClass2</code> are normal template classes.</p>
  
  <pre><code>class MyClass1( val id: String, val data: String)
  </code></pre>
  
  <p>Is there any smart way to cast response body to my custom classes?</p>
  
  <p><strong>Small update for MyClass2</strong></p>
  
  <pre><code>class MyClass2( val token: String, val url: String, val quantity: Int)
  </code></pre>