I’m working on a web app that uses JSON for client-server communication. Some client-side code:
class Result(val things: ArrayList<Thing>, val time: Double) … asyncRequest.success = { result -> for (t in result.things) { // make dom for a table row } }
I get an error, since things is really a plain JS array, from a JSON response. Error: ‘undefined’ is not a function (evaluating ‘result.things.iterator()’).
If I can see how ArrayList (in JS) is implemented, maybe I can write some native JS to fix this.
I have a reason not to use Array<Thing>, which I could explain more. Basically, I’m trying to reuse code for the Result class, for server side.
Do not forget implementation details can be changed in the future.
Other possible solutions:
cast things before using, like: result.things as Array<Thing>
or write helper function/property which do that if you don’t want write Array type parameter everytime, like:
fun ArrayList<Thing>.asArray(): Thing = this as Array<Thing>
// or fun Result.thingsAsArray() = thigs as Array<Thing>
// or
val Result.thingsAsArray: Array<Thing>
get() = thigs as Array<Thing>
make container class as generic parameter of Result, like: class Result<C>(val things: C<Thing>, val time: Double) Result(listOf(“a”, “b”), 1.1)
Result(array(“1”, “2”), 1.1)
make container class as generic parameter of Result, like: class Result<C>(val things: C<Thing>, val time: Double) Result(listOf(“a”, “b”), 1.1)
Result(array(“1”, “2”), 1.1)
That’s interesting. I didn’t know Kotlin had “higher kinded” types. … (if that’s what that is. )
Thanks for the pointers. I’ll try a few different ways and see how they work out.