1

my question is about creating javascript structure within KotlinJS and use them calling external modules. Let's say we have the following js code and we want to translate it into KotlinJS.

const config = {
defs : "something",
resolvers : {
  Query: {
    books: () => []
  }}
};

myFunction(config) // This can be any kind of external js function that accepts the above structure

How do we represent that config structure above using Kotlin JS? Is there an easy way to handle structures/json Kotlin side? Can we declare in some way that structure as dynamic? Using Kotlin objects doesn't help.

1 Answer 1

1

As of now you gotta introduce interface and it's implementation, so it would be something like this:

external interface ConfigInterface {
  var defs: String,
  var resolvers: QueryHolder
}

external interface QueryHolder {
   var Query: BookProcessor
}

external interface BookProcessor {
   var books: () -> Array<Any>
}

For more complicated structures it can easily become a challenge. Here's what can be done to automate such translations. You can:

  • generate typescript declaration for this code with typescript compiler (using tsc -d)
  • generate kotlin declaration with dukat.

Dukat is a tool from Kotlin/JS team created specifically for this, there's ongoing battle for improving the quality of this tool. Here is what would be generated in your particular case:

external interface `T$0` {
    var books: () -> Array<Any>
}

external interface `T$1` {
    var Query: `T$0`
}

external object config {
    var defs: String
    var resolvers: `T$1`
}

Which is far from optimal - for instance the name of generated entities is something we didn't wanted to encourage people to reuse but the more it goes, the more it looks like a mistake (which we will fix this way or another).

Sign up to request clarification or add additional context in comments.

2 Comments

I know you "well". I did read part of the dukat code and I saw you many times. It helped me to understand a lot better how to deal with Kotlin/JS interoperability. I am glad you answered, that was the bit I was missing. I was using objects instead of interfaces and the generated code was not what I did expect. I did ask the same question in Kotlin Discussion but no one answered => discuss.kotlinlang.org/t/… If you don't mind I can put your answer there too mentioning you as author. May I? Thanks
@Jac sure, feel free to quote/link any public answer whatever way you want!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.