There is no native keyword, there is an @native annotation. This is currently a working solution, and you can use it with the 1.0.x branch of the Kotlin compiler. However, we are going to denounce this annotation in favor of extern annotations, so be prepared to rewrite the code at the end for the 1.1.x branch.
When you put the @native annotation in a class or top-level function, two things happen:
- His body is not compiled for JavaScript.
- The compiler refers to this class or function directly, without the package name and mangling.
I think this is easier to explain by providing an example JavaScript library:
function A(x) { this.x = x; this.y = 0; } A.prototype.foo = function(z) { return this.x + this.y + z; } function min(a, b) { return a < b ? a : b; }
and the corresponding Kotlin declaration
@native class A(val x: Int) { var y: Int = noImpl fun foo(z: Int): Int = noImpl } @native fun min(a: Int, b: Int): Int = noImpl
Note that noImpl is a special placeholder that is required due to non-abstract functions, required bodies, and non-abstract properties that initializers require. BTW, when we replace @native with extern , we will get rid of this noImpl .
Another aspect of interacting with JS libraries is the inclusion of libraries through a modular system. Unfortunately, we do not have any solution now (but we will publish it soon). See proposal . You can use the following workaround for node.js / CommonJS:
@native interface ExternalModule { fun foo(x: Int) } @native fun require(name: String): dynamic = noImpl fun main(args: Array<String>) { val module: ExternalModule = require("externalModule") module.foo(123) }
where the external module is declared as follows
function foo(x) { return x + 1; } module.exports = { foo : foo };
Alexey Andreev
source share