Skip to content

Language Guide: Advanced Features

This section covers advanced Kotlin language features and their C++ transpilation.

Generics

ktox-cpp transpiles Kotlin generics to C++ templates.

Kotlin:

class Box<T>(val value: T)

fun <T> identity(item: T): T = item

C++:

template <typename T>
class Box {
public:
    T value;
    Box(T value) : value(value) {}
};

template <typename T>
T identity(T item) {
    return item;
}

Lambdas & Higher-Order Functions

Kotlin lambdas are transpiled to C++ lambdas with a capture-all by reference ([&]).

Kotlin:

val multiply = { x: Int, y: Int -> x * y }

fun <T> T.let(block: (T) -> Unit) {
    block(this)
}

C++:

const auto multiply = [&](auto x, auto y) {
    return x * y;
};

template <typename T, typename F>
void let(T self, F block) {
    block(self);
}

Collections & Standard Library

ktox-cpp provides a runtime library (ktox-lib.hpp) that maps Kotlin's standard library functions to C++ using std::vector and std::unordered_map.

Kotlin:

val list = listOf(1, 2, 3)
val doubled = list.map { it * 2 }
val evens = list.filter { it % 2 == 0 }

C++:

const auto list = std::vector<int32_t>{1, 2, 3};
const auto doubled = ktox::map(list, [&](auto it) { return it * 2; });
const auto evens = ktox::filter(list, [&](auto it) { return it % 2 == 0; });

Exception Handling

Kotlin's try-catch blocks map to C++ try-catch. Standard Kotlin exceptions are mapped to their <stdexcept> equivalents.

Kotlin Exception C++ Exception
RuntimeException std::runtime_error
IllegalArgumentException std::invalid_argument
IllegalStateException std::logic_error
IndexOutOfBoundsException std::out_of_range
Exception std::exception

Kotlin:

try {
    performAction()
} catch (e: Exception) {
    println("Error: ${e.message}")
}

C++:

try {
    performAction();
}
catch (std::exception& e) {
    println("Error: " + ktox::toString(e.what()) + "");
}

Finally blocks

Kotlin's finally blocks are transpiled using RAII via ktox::ScopeGuard to ensure they run even if an exception is thrown or a return is executed.

Kotlin:

try {
    doWork()
} catch (e: Exception) {
    handle(e)
} finally {
    cleanup()
}

C++:

{
    auto __finally = ktox::ScopeGuard([&] {
        cleanup();
    });
    try {
        doWork();
    }
    catch (std::exception& e) {
        handle(e);
    }
}

Other Features

Destructuring Declarations

ktox-cpp supports Kotlin's destructuring declarations using C++17 structured bindings.

Kotlin:

val (a, b) = p

C++:

const auto [a, b] = p;

Type Aliases

Kotlin typealias is transpiled to a C++ using declaration.

Kotlin:

typealias StringList = List<String>

C++:

using StringList = std::vector<std::string>;

Noreturn Functions

Functions returning Nothing are marked with the [[noreturn]] attribute in C++.

Kotlin:

fun fail(): Nothing = throw RuntimeException("fail")

C++:

[[noreturn]] void fail() {
    throw std::runtime_error("fail");
}

Annotations

Annotations can be used to control the transpilation process.

Kotlin:

@NativeName("external_func")
fun myFunc() { }

C++:

// Emitted as:
void external_func() { }