Basics & Core Concepts¶
This section covers the fundamental building blocks of ktox-cpp and how Kotlin's basic syntax maps to C++.
Packages and Namespaces¶
ktox-cpp handles Kotlin packages by transpiling them into C++ namespaces and directory structures.
Kotlin:
C++ (transpiled as math/Calculator.hpp):
Variables (val vs var)¶
Kotlin's distinction between immutable (val) and mutable (var) variables is preserved. val becomes const auto and var becomes auto.
Kotlin:
C++:
Basic Types¶
Kotlin types are mapped to their standard C++ equivalents from <cstdint> and std.
| Kotlin Type | C++ Type | Notes |
|---|---|---|
Int |
int32_t |
|
Long |
int64_t |
|
Float |
float |
|
Double |
double |
|
String |
std::string |
|
Boolean |
bool |
|
List, Map |
std::vector, std::unordered_map |
From <vector> and <unordered_map> |
null |
std::nullopt |
Uses std::optional for nullable types |
Functions¶
Top-level functions in Kotlin become free functions within the appropriate namespace in C++.
Kotlin:
fun greet(name: String): String {
return "Hello, $name!"
}
private fun internalCalc(x: Int): Int = x * 2
C++:
std::string greet(std::string name) {
return "Hello, " + ktox::toString(name) + "!";
}
// private visibility is handled at the transpilation level
int32_t internalCalc(int32_t x) {
return x * 2;
}
String Interpolation & Templates¶
Kotlin's string interpolation is transpiled into C++ string concatenation using ktox::toString() for non-string types. Note that the transpiler often wraps parts in empty strings to ensure correct std::string concatenation.
Kotlin:
val count = 5
val message = "The count is $count"
val lang = "Lua"
val msg2 = "Running on $lang ${version + 0}"
C++:
const auto count = 5;
const auto message = "The count is " + ktox::toString(count) + "";
const auto lang = "Lua";
const auto msg2 = "Running on " + ktox::toString(lang) + " " + ktox::toString(version + 0) + "";
Control Flow¶
If Expressions¶
In Kotlin, if is an expression. ktox-cpp transpiles simple if expressions to the C++ ternary operator or an Immediately Invoked Lambda Expression (IILE) for complex blocks.
Kotlin:
C++:
When Expressions¶
Kotlin's when expression is transpiled into an if-else chain, often wrapped in an IILE if used as an expression.
Kotlin:
C++:
const auto color = [&]() {
if (id == 1) return "Red";
else if (id == 2) return "Green";
else return "Unknown";
}();
For Loops and Ranges¶
ktox-cpp optimizes Kotlin ranges into efficient C++ for loops. Note that it explicitly uses += 1 or -= 1 for increments.
Kotlin:
for (i in 1..5) {
sum += i
}
for (i in 0 until 5) {
println(i)
}
for (i in 5 downTo 1 step 2) {
println(i)
}
C++:
for (auto i = 1; i <= 5; i += 1) {
sum = sum + i;
}
for (auto i = 0; i < 5; i += 1) {
println(i);
}
for (auto i = 5; i >= 1; i -= 2) {
println(i);
}
While Loops¶
while and do-while loops map directly to their C++ equivalents.
Kotlin:
C++: