首页 > 解决方案 > 在 Javascript 后端使用无符号数字类型

问题描述

我想在 Javascript 后端使用 Kotlin 的无符号数字类型;也就是说,我想使用编写 Kotlin 代码UByte并将其编译为 JS。

我编写了以下测试程序:

@kotlin.ExperimentalUnsignedTypes
fun main(args: Array<String>) {
    val x : UByte = 1u
    println(x)
}

我可以用 JVM 后端编译和运行它:

$ kotlinc-1.3.70/bin/kotlinc hello.kt -include-runtime -d hello.jar
$ java -jar hello.jar 
1

但是如果我将它编译为 Javascript 并尝试将输出加载到浏览器中,它会失败:

$ kotlinc-1.3.70/bin/kotlinc-js hello.kt -output hello.js
<html>
  <head>
    <title>Unsigned</title>
    <script src="kotlin.js"></script>
    <script src="kotlin.meta.js"></script>
    <script src="hello.js"></script>
  </head>
  <body>
  </body>
</html>

我什至没有尝试调用hello.main,它已经在页面加载时失败了:

Uncaught TypeError: UByte is not a constructor
    at main (hello.js:8)
    at hello.js:12
    at hello.js:15

如果有帮助,生成的 JS 如下:

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

我缺少什么与UByte等人一起工作。在编译为 Javascript 的 Kotlin 代码中?

标签: javascriptkotlinnumbersunsigned

解决方案


推荐阅读