Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin conversion to Javascript error: "subtract is not a function"

I'm having an issue when converting a Kotlin code to JavaScript. Whenever I use subtraction or addition, it converts to an invalid JavaScript code.

I have a Kotlin JavaScript project, configured with Gradle. The compiler is configured to generate output to commonjs, and I created a simple NodeJS application to execute the generated code.

Original Kotlin file:

import kotlin.js.JsName

@JsName("testSubtraction")
fun testSubtraction(a: Long, b: Long) : Long {
    return a - b
}

Generated output file:

module.exports = function (Kotlin) {
  'use strict';
  var _ = Kotlin.defineRootPackage(null, /** @lends _ */ {
    testSubtraction: function (a, b) {
      return a.subtract(b);
    }
  });
  Kotlin.defineModule('output', _);
  return _;
}(require('kotlin'));

//@ sourceMappingURL=output.js.map

The error that I get when executing the code is: TypeError: a.subtract is not a function

I have tested using Kotlin 1.0.5-2 and 1.1-M03, but they both convert with this same problem.

How do I solve this problem?

The workaround solution that I have found so far is defining this method manually in my application, but I didn't like it:

Number.prototype.subtract = function(a) {
    return this.valueOf() - a;
}

I have created a sample project to demonstrate this issue at GitHub: https://github.com/leandro-dev/test_kotlin_js

like image 374
Leandroid Avatar asked Dec 04 '25 16:12

Leandroid


1 Answers

Kotlin Long is not JS number and the problem is that you call testSubtraction with JS numbers.

If you want to work with JS number use Int in Kotlin code.

If you want to pass JS number where Kotlin expected Long use Kotlin.Long.fromNumber or Kotlin.Long.fromInt to create Long

like image 63
bashor Avatar answered Dec 06 '25 06:12

bashor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!