Skip to content

Classes & Objects

Classes

Kotlin classes transpile to ES6 classes. Properties in the primary constructor are automatically assigned in the JS constructor.

class Person(val name: String, var age: Int) {
    fun greet() {
        println("Hello, " + name)
    }
}

Transpiles to:

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    greet() {
        println("Hello, " + name);
    }
}

Inheritance

Inheritance is supported via ES6 extends and super().

open class Animal(val name: String)
class Dog(name: String) : Animal(name)

Transpiles to:

class Animal {
    constructor(name) {
        this.name = name;
    }
}

class Dog extends Animal {
    constructor(name) {
        super(name);
    }
}

Interfaces

Interfaces are not emitted at runtime because JavaScript does not have a native runtime representation for them. They are only used for compile-time checks in Kotlin.

interface Printable {
    fun print()
}

Transpiles to:

// interface Printable (not emitted; JS has no interface runtime representation)

Enums

Enums are transpiled to frozen JavaScript objects.

enum class Color {
    RED, GREEN, BLUE
}

Transpiles to:

const Color = Object.freeze({
    RED: "RED",
    GREEN: "GREEN",
    BLUE: "BLUE",
});

Objects

Singletons declared with object are transpiled to frozen JavaScript objects.

object Registry {
    val entries = mutableListOf<String>()
}

Transpiles to:

const Registry = Object.freeze({
    entries: ktox_mutableListOf(),
});