How to call from Javascript a method define in Kotlin in a Kvision project

80 Views Asked by At

I have a Kotlin/JS project, using Kvision (I think started from a Kvision template) My build.gradle.kts looks like this https://ideone.com/yOEcMF

Questions:

  1. How do I call from JS code a function defined by me in Kotlin? Say I have this in .kt file :

    package com.zzz

    class KotlinHelper {

     fun doXXX(str: String): Int = str.length
    
     fun doYYY(bytes: ByteArray): String = bytes.decodeToString()
    

    }

    val kotlinHelper = KotlinHelper()

I want to call it from Javascript +/- like this

kotlinHelper.doXXX("something");

(the other way around I managed, meaning call from Kotlin code defined in JS - by use of "external" modifier on Kotlin class & actual implementation in JS) Found this https://kotlinlang.org/docs/js-to-kotlin-interop.html .. but still didn't managed.

  1. Can you explain how this works ? My Kotlin code + whatever Kotlin + Kvision brings seem to get bundled & transpiled to Javascript in "main.bundle.js" Code also seems obfuscated & minified.. I obviously want to call method with the name that I defined it have - is this possible? Is the Kotlin code, that is not used - removed?
1

There are 1 best solutions below

0
pulancheck1988 On

worked like this

Call from JS

new KTJS_Kvision.com.xxx.yyy.KotlinHelper().doXXX("Ana")

KTJS_Kvision - is my project name

com.xxx.yyy.KotlinHelper is the full name of class (incl packageName)

I also have these annotations:

@JsExport
class KotlinHelper {
    @JsName("doXXX")
    fun doXXX(str: String): Int = str.length
...