Search code examples
kotlinkotlin-interop

'x' is not a function when passing parameters in Kotlin Javascript


I keep getting this error: TypeError: Scraper.dumpTitle is not a function

And I can't figure out why...

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Kotlin JS Demo</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script src="out/production/lib/kotlin.js"></script>
<script src="out/production/Scraper.js"></script>
    <!--<script>-->
        <!--function loaded() {-->
        <!--}-->
    <!--</script>-->

    <script>
        $(function() {
            Scraper.dumpTitle(document)
        })

    </script>

</body>
</html>

Main.js

import kotlin.browser.document

/**
 *  *
 *  * -
 */
fun main(args: Array<String>) {
    println("Hello")
}

fun dumpTitle(doc: dynamic) {
    println(doc.title)
}
fun dumpTitle1() {
    println(document.title)
}

generated js

if (typeof kotlin === 'undefined') {
  throw new Error("Error loading module 'Scraper'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'Scraper'.");
}
var Scraper = function (_, Kotlin) {
  'use strict';
  var println = Kotlin.kotlin.io.println_s8jyv4$;
  function main(args) {
    println('Hello');
  }
  function dumpTitle(doc) {
    println(doc.title);
  }
  function dumpTitle1() {
    println(document.title);
  }
  _.main_kand9s$ = main;
  _.dumpTitle_za3rmp$ = dumpTitle;
  _.dumpTitle1 = dumpTitle1;
  Kotlin.defineModule('Scraper', _);
  main([]);
  return _;
}(typeof Scraper === 'undefined' ? {} : Scraper, kotlin);

notes

  1. calling dumpTitle1() works fine.. so the problem I have is only with passing parameters
  2. no need to point out that I can access the document variable in Kotlin without needing to pass it, I know... but I wanted to pass another document object to use

Solution

  • If you're calling a Kotlin function from JavaScript, you need to use the @JsName annotation to give it a stable name. See here for documentation.

    @JsName("dumpTitle")
    fun dumpTitle(doc: dynamic) {
        println(doc.title)
    }