【问题标题】:How to convert JS code to Kotlin without the 'new' keyword如何在没有“new”关键字的情况下将 JS 代码转换为 Kotlin
【发布时间】:2018-02-25 07:08:54
【问题描述】:

我正在考虑将一些基本的 JS 转换为 Kotlin,但我坚持使用 new 关键字。我不确定如何将以下 JS 转换为 Kotlin

var FCM = require('fcm-node');
var fcm = new FCM('YOURSERVERKEYHERE');
var message = { ... };
fcm.send(message, function(err, response){ ... }

我试过了

fun sendTestPush() {
  val FCM = require("fcm-push")
  val fcm = new FCM("YOURSERVERKEYHERE")

  val data = Data("Title", "Message")
  val message = Message("registration_id", data)

  fcm.send(message)
}

data class Message(val to: String, val data: Data)
data class Data(val title: String, val message: String)

我收到编译错误Unresolved reference: new,因为 Kotlin 没有它。 如果没有“新”,我会收到预期的错误Attempting to TypeError: Cannot read property 'send' of undefined

有解决这个问题的办法吗?

编辑:FCM 类是 npm 包https://www.npmjs.com/package/fcm-push

【问题讨论】:

标签: javascript firebase kotlin firebase-cloud-messaging


【解决方案1】:

抱歉,您标记为正确的答案实际上是不正确的。我不得不这么说,因为寻找正确答案的人可能会找到它并编写错误的代码。通常,您不应直接从 Kotlin 调用 require 函数。相反,您应该将@JsModuleexternal 声明一起使用。在您的特定情况下,它将是这样的:

@JsModule("fcm-push")
external class FCM(serverKey: String) {
   fun send(message: Any?, callback: (err: Any?, response: Any?) -> Unit)
   fun send(message: Any?): Promise<Any>
}

val serverKey = "YOURSERVERKEYHERE"
val fcm = FCM(serverKey)
//...
fcm.send(message)

此外,您应该将commonjs 传递给moduleKind 编译器标志。有关完整说明,请参阅corresponding documentation page

【讨论】:

  • 传奇,谢谢。我确实必须让它external class FCM(key: String) { 接受 serverKey in. 标记为已接受。我还不确定如何处理代码的回调或承诺部分,但也许这应该是另一个问题
【解决方案2】:

require function in Kotlin 与您的 JS 代码中可能使用的 require in NodeJS 不同。

无论您的 FCM 类是什么,只需在没有 new 关键字的情况下实例化它即可。

【讨论】:

  • 抱歉添加了一个编辑,它的 fcm-push npm 模块来自这里 npmjs.com/package/fcm-push 。它仅适用于带有new 的 NodeJS,并且无法弄清楚如何在 kotlin 中运行
  • @JaredHall 我想我误解了这个问题,您仍然希望您的代码编译为 JS,而不是“转移”到 JVM 上的 Kotlin,对吧?
  • 正确。我认为对我来说最好的学习方式是首先在我较大的 nodejs 项目中开始将一些较小的类转换为 kotlin
【解决方案3】:

感谢@Claies 的提示,我设法使用js(...) wrap 让它工作。~~~

val FCM = require("fcm-push")
val serverKey = "YOURSERVERKEYHERE"
val fcm = js("new FCM(serverKey)")
...
fcm.send(message) // now works

我不确定我是否对在 kotlin 中的字符串中编写纯 js 完全满意,所以我希望有更好的方法我错过了。

编辑:上述方法可行,但并不理想,请参阅接受的答案以获得更好的实施

【讨论】:

    猜你喜欢
    • 2019-10-20
    • 2022-11-21
    • 1970-01-01
    • 2020-03-16
    • 2020-02-06
    • 2011-12-07
    • 2014-12-28
    • 1970-01-01
    • 2017-05-20
    相关资源
    最近更新 更多