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:
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:
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:
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:
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:
C++:
Type Aliases¶
Kotlin typealias is transpiled to a C++ using declaration.
Kotlin:
C++:
Noreturn Functions¶
Functions returning Nothing are marked with the [[noreturn]] attribute in C++.
Kotlin:
C++:
Annotations¶
Annotations can be used to control the transpilation process.
Kotlin:
C++: