【问题标题】:What is the purpose of actual keyword in KotlinKotlin中实际关键字的目的是什么
【发布时间】:2018-02-14 19:35:05
【问题描述】:

我注意到协程的一些函数标有actual 关键字。

来自documentation

actual 表示多平台中特定于平台的实现 项目

据我了解,documentation actual 关键字用于多平台项目,应与 expect 关键字配对使用。

类似这样的:

通用模块:

package org.jetbrains.foo

expect class Foo(bar: String) {
    fun frob()
}

fun main(args: Array<String>) {
    Foo("Hello").frob()
}

对应模块:

package org.jetbrains.foo

actual class Foo actual constructor(val bar: String) {
    actual fun frob() {
        println("Frobbing the $bar")
    }
}

这个案子很清楚。

但是在kotlinx.coroutines.experimental 包中,我注意到launchwithContext 等一些函数被标记为actual,但包中没有expect 函数。

那么actual关键字没有expect的目的是什么?

【问题讨论】:

标签: kotlin


【解决方案1】:

kotlinx.coroutines 库实际上利用了多平台项目,因为它同时支持 JVM 和 JS 编译目标。

您可以找到通用模块here,以及您提到的函数here 的特定expect 声明。

【讨论】:

  • 那么这仅适用于期望/实际对。谢谢!
  • 我在此链接中找到了有关expectactual 在多平台实现中使用的更多信息:kotlinlang.org/docs/reference/…
  • 我在第二个链接中找不到expect 声明。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-16
  • 1970-01-01
  • 2021-01-11
  • 2016-06-03
  • 2015-06-07
  • 2019-08-21
相关资源
最近更新 更多