kotlinscript
v2.0.0
Published
🎯 Kotlin syntax running on Node.js | Write Kotlin, Execute JavaScript
Downloads
14
Maintainers
Readme
🎯 KotlinScript
Write Kotlin, Execute JavaScript
Part of the CapybaraScript Company 🦫
English
🎯 Kotlin syntax that runs on Node.js. No JVM required!
KotlinScript is a transpiler that converts Kotlin-like syntax into JavaScript, allowing you to write code with Kotlin's modern syntax while leveraging the entire Node.js ecosystem.
✨ Features
- 🎯 Kotlin syntax - Write code that looks and feels like Kotlin
- ⚡ Runs on Node.js - No JVM or Kotlin compiler needed
- 🔄 Real-time transpilation - Converts your code on the fly
- 📦 Easy to use - Simple CLI interface
- 🎨 Beautiful error messages - Clear and helpful error reporting
- 🦫 By CapybaraScript - Open source language distribution
🚀 Installation
npm install -g kotlinscriptOr use it locally:
npm install kotlinscript📖 Quick Start
Command Line:
# Run a KotlinScript file
kotlinscript myfile.kt
# Or use the short alias
kt myfile.ktProgrammatic:
const KotlinScript = require('kotlinscript');
const code = 'println("Hello from Kotlin!")';
KotlinScript.run(code);🎓 Syntax Guide
Print/Output:
println("Hello, World!")
print("No newline")
println("Value: $value")Variables:
val name = "Kotlin" // immutable
var age = 5 // mutable
val active: Boolean = true
val nothing: String? = nullFunctions:
fun greet(name: String) {
println("Hello, $name!")
}
fun add(a: Int, b: Int): Int {
return a + b
}
// Single expression
fun multiply(a: Int, b: Int) = a * b
val result = add(5, 3)
greet("Developer")String Templates:
val name = "Kotlin"
println("Hello, $name!")
println("2 + 2 = ${2 + 2}")
println("Length: ${name.length}")Conditionals:
val max = if (a > b) a else b
when (x) {
1 -> println("One")
2 -> println("Two")
else -> println("Other")
}
if (age > 18) {
println("Adult")
} else if (age > 13) {
println("Teen")
} else {
println("Child")
}Loops:
// Range
for (i in 1..5) {
println(i)
}
// Until (exclusive)
for (i in 0 until 10) {
println(i)
}
// Step
for (i in 0..10 step 2) {
println(i)
}
// Collection
val fruits = listOf("apple", "banana")
for (fruit in fruits) {
println(fruit)
}
// While
var count = 0
while (count < 5) {
println(count)
count++
}Collections:
// List
val fruits = listOf("apple", "banana", "orange")
val mutableList = mutableListOf(1, 2, 3)
mutableList.add(4)
println(fruits[0])
println(fruits.size)
// Map
val person = mapOf(
"name" to "Alice",
"age" to 30
)
println(person["name"])
// Mutable Map
val mutableMap = mutableMapOf<String, Int>()
mutableMap["key"] = 42Data Classes:
data class Person(val name: String, val age: Int) {
fun greet() {
println("Hi, I'm $name")
}
}
val p = Person("Alice", 30)
p.greet()
println(p.name)Classes:
class Person(val name: String, var age: Int) {
fun greet() {
println("Hi, I'm $name, $age years old")
}
fun birthday() {
age++
}
}
val p = Person("Bob", 25)
p.greet()
p.birthday()Lambda Functions:
val numbers = listOf(1, 2, 3, 4, 5)
numbers.forEach { num ->
println(num)
}
val doubled = numbers.map { it * 2 }
val evens = numbers.filter { it % 2 == 0 }
val sum = numbers.reduce { acc, num -> acc + num }Null Safety:
var name: String? = null
println(name?.length) // Safe call
println(name ?: "Default") // Elvis operator
val length = name?.length ?: 0Extension Functions:
fun String.shout(): String {
return this.uppercase() + "!"
}
println("hello".shout()) // "HELLO!"Try/Catch:
try {
riskyOperation()
} catch (e: Exception) {
println("Error: ${e.message}")
} finally {
println("Cleanup")
}Imports:
import "fs"
import "path" as pathModule
val content = fs.readFileSync("file.txt", "utf8")🎯 Complete Examples
Fibonacci:
fun fibonacci(n: Int): Int {
return if (n <= 1) n else fibonacci(n - 1) + fibonacci(n - 2)
}
fun main() {
for (i in 0..10) {
println("Fib($i) = ${fibonacci(i)}")
}
}
main()Person Manager:
data class Person(val name: String, var age: Int) {
fun greet() = println("Hi, I'm $name")
fun haveBirthday() { age++ }
}
fun main() {
val people = mutableListOf(
Person("Alice", 30),
Person("Bob", 25),
Person("Charlie", 35)
)
people.forEach { it.greet() }
val adults = people.filter { it.age >= 30 }
println("Adults: ${adults.size}")
people.forEach { it.haveBirthday() }
println("After birthdays:")
people.forEach {
println("${it.name} is now ${it.age}")
}
}
main()Simple Web Server:
import "http"
fun handleRequest(req: Any, res: Any) {
res.writeHead(200, mapOf("Content-Type" to "text/plain"))
res.end("Hello from KotlinScript!")
}
fun main() {
val server = http.createServer(::handleRequest)
server.listen(3000)
println("🎯 Server running on port 3000")
}
main()Number Processing:
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
println("Original: $numbers")
val doubled = numbers.map { it * 2 }
println("Doubled: $doubled")
val evens = numbers.filter { it % 2 == 0 }
println("Evens: $evens")
val sum = numbers.reduce { acc, n -> acc + n }
println("Sum: $sum")
val bigNumbers = numbers.filter { it > 5 }
.map { it * 3 }
println("Big numbers tripled: $bigNumbers")
}
main()🔧 How It Works
KotlinScript transpiles Kotlin-like syntax to JavaScript:
- Parses Kotlin-style code
- Converts to equivalent JavaScript
- Executes in Node.js runtime
💡 Why KotlinScript?
- Learn Kotlin syntax while using Node.js ecosystem
- Android developers can use familiar syntax in backend
- Modern features like data classes, lambdas, null safety
- No JVM needed - runs directly on Node.js
- Part of CapybaraScript family 🦫
📧 Contact
- Company: CapybaraScript 🦫
- Author: capybarascript
- Email: [email protected]
- npm: npmjs.com/package/kotlinscript
📝 License
MIT License - Free to use in your projects!
Português
🎯 Sintaxe Kotlin rodando no Node.js. Sem necessidade de JVM!
KotlinScript é um transpilador que converte sintaxe estilo Kotlin em JavaScript, permitindo que você escreva código com a sintaxe moderna do Kotlin enquanto aproveita todo o ecossistema do Node.js.
✨ Recursos
- 🎯 Sintaxe Kotlin - Escreva código que parece e funciona como Kotlin
- ⚡ Roda no Node.js - Sem necessidade de JVM ou compilador Kotlin
- 🔄 Transpilação em tempo real - Converte seu código na hora
- 📦 Fácil de usar - Interface CLI simples
- 🎨 Mensagens de erro bonitas - Relatórios claros e úteis
- 🦫 Por CapybaraScript - Distribuição open source de linguagens
🚀 Instalação
npm install -g kotlinscriptOu use localmente:
npm install kotlinscript📖 Começando
Linha de comando:
# Execute um arquivo KotlinScript
kotlinscript meuarquivo.kt
# Ou use o alias curto
kt meuarquivo.ktProgramático:
const KotlinScript = require('kotlinscript');
const codigo = 'println("Olá do Kotlin!")';
KotlinScript.run(codigo);🎓 Guia de Sintaxe
Print/Saída:
println("Olá, Mundo!")
print("Sem quebra de linha")
println("Valor: $valor")Variáveis:
val nome = "Kotlin" // imutável
var idade = 5 // mutável
val ativo: Boolean = true
val nada: String? = nullFunções:
fun saudar(nome: String) {
println("Olá, $nome!")
}
fun somar(a: Int, b: Int): Int {
return a + b
}
// Expressão única
fun multiplicar(a: Int, b: Int) = a * b
val resultado = somar(5, 3)
saudar("Desenvolvedor")Coleções:
// Lista
val frutas = listOf("maçã", "banana", "laranja")
val listaEditavel = mutableListOf(1, 2, 3)
listaEditavel.add(4)
println(frutas[0])
println(frutas.size)
// Mapa
val pessoa = mapOf(
"nome" to "Alice",
"idade" to 30
)Data Classes:
data class Pessoa(val nome: String, val idade: Int) {
fun saudar() {
println("Oi, eu sou $nome")
}
}
val p = Pessoa("Alice", 30)
p.saudar()Lambdas:
val numeros = listOf(1, 2, 3, 4, 5)
numeros.forEach { num ->
println(num)
}
val dobrados = numeros.map { it * 2 }
val pares = numeros.filter { it % 2 == 0 }🎯 Exemplos Completos
Fibonacci:
fun fibonacci(n: Int): Int {
return if (n <= 1) n else fibonacci(n - 1) + fibonacci(n - 2)
}
fun main() {
for (i in 0..10) {
println("Fib($i) = ${fibonacci(i)}")
}
}
main()Processamento de Números:
fun main() {
val numeros = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
println("Original: $numeros")
val dobrados = numeros.map { it * 2 }
println("Dobrados: $dobrados")
val pares = numeros.filter { it % 2 == 0 }
println("Pares: $pares")
val soma = numeros.reduce { acc, n -> acc + n }
println("Soma: $soma")
}
main()🔧 Como Funciona
KotlinScript transpila sintaxe Kotlin para JavaScript:
- Analisa código estilo Kotlin
- Converte para JavaScript equivalente
- Executa no runtime do Node.js
💡 Por Que KotlinScript?
- Aprenda sintaxe Kotlin usando ecossistema Node.js
- Desenvolvedores Android podem usar sintaxe familiar no backend
- Recursos modernos como data classes, lambdas, null safety
- Sem JVM - roda direto no Node.js
- Parte da família CapybaraScript 🦫
📧 Contato
- Empresa: CapybaraScript 🦫
- Autor: capybarascript
- Email: [email protected]
- npm: npmjs.com/package/kotlinscript
📝 Licença
Licença MIT - Livre para usar nos seus projetos!
Made with 💙 by CapybaraScript Company 🦫
Part of the open source language distribution family
