1

Not sure if this is a discrepancy in the type cast or I am using it wrong. The direct cast throws an error but using generic cast will make my code work.

Below I am trying to cast a Json to Person

import kotlin.js.Json

data class Person(val name: String)

fun main(args: Array<String>) {

    val persons: Json = JSON.parse("""{ "p1": { name: "foo" } } """)

    val p1: Person = persons.get("p1") as Person    // throws ClassCastException("Illegal cast")

    fun <T> Json.typedGet(s: String): T = this.get(s) as T
    val p2: Person = persons.typedGet("p1")         // but this works!!

}

The direct cast seem to generate code that checks actual Person class

val p1: Person = persons.get("p1") as Person 

// generated javascript (note type check with *Person*)
// var p1 = Kotlin.isType(tmp$ = persons['p1'], Person) ? tmp$ : Kotlin.throwCCE()

The generic cast seem to generate code that checks with Any

fun <T> Json.typedGet(s: String): T = this.get(s) as T
val p2: Person = persons.typedGet("p1")  

// generates javascript (note type check with *Any*)
// var p1 = Kotlin.isType(tmp$ = persons['p1'], Any) ? tmp$ : Kotlin.throwCCE()

Should we always be using Generic cast? Or is there some right way to do this?

Krishna K
  • 1,925
  • 1
  • 14
  • 11

0 Answers0