文档/参考/内置函数

内置函数

NovaLang 内置函数与类型方法完整参考

内置函数

I/O

println("Hello")          // 输出并换行
print("Hello")            // 输出不换行
readLine()                // 读取一行输入
input("请输入名字: ")      // 带提示读取输入

数学函数

abs(-5)           // 5
max(3, 7)         // 7
min(3, 7)         // 3
sqrt(16.0)        // 4.0
pow(2.0, 10.0)    // 1024.0
floor(3.7)        // 3.0
ceil(3.2)         // 4.0
round(3.5)        // 4.0
sign(-42)         // -1
clamp(15, 0, 10)  // 10
random()          // 0.0~1.0 随机数

三角函数:sin / cos / tan / asin / acos / atan / atan2

对数函数:log (自然) / log10 / log2 / exp

随机数

randomInt(1, 100)         // 随机整数 [1, 100]
randomDouble(0.0, 1.0)    // 随机浮点 [0.0, 1.0)
randomBool()              // 随机布尔值
randomStr("abc123", 8)    // 从字符集生成 8 位随机字符串
randomList(1, 100, 10)    // 10 个 [1,100] 随机整数列表

类型转换

toInt("42")       // 42
toLong("123")     // 123L
toDouble("3.14")  // 3.14
toString(42)      // "42"
toBoolean("true") // true
toChar(65)        // 'A'

类型检查

typeof(42)         // "Int"
isNull(null)       // true
isNumber(3.14)     // true
isString("hi")     // true
isList([1,2])      // true
isMap(#{})         // true
isCallable(println) // true
len([1, 2, 3])     // 3

集合创建

listOf(1, 2, 3)            // 不可变列表
mutableListOf(1, 2, 3)     // 可变列表
emptyList()                // 空列表
mapOf("a" to 1, "b" to 2) // 不可变 Map
mutableMapOf()             // 可变 Map
setOf(1, 2, 3)             // 不可变 Set
arrayOf(1, 2, 3)           // 数组
range(0, 10)               // 半开区间 [0, 10)
rangeClosed(1, 10)         // 闭区间 [1, 10]
pairOf("name", "Nova")    // Pair

构建器模式:

val list = buildList {
    add(1)
    add(2)
    add(3)
}
val str = buildString {
    append("Hello")
    append(", ")
    append("Nova!")
}

工具函数

error("出错了")                    // 抛出异常
check(x > 0, "x 必须为正数")       // 条件检查
require(x > 0, "x 必须为正数")     // 前置条件断言
checkNotNull(value, "不能为 null")  // 非空检查
with(obj) { method1(); method2() } // 作用域函数
repeat(3) { println("hi") }       // 重复执行

// 性能测量
val ms = measureTimeMillis { heavyWork() }
println("耗时: ${ms}ms")

// 异常捕获
val result = runCatching { riskyOperation() }

Result 类型

runCatching 返回 Result 类型,提供安全的错误处理链:

val result = runCatching { parseInt("abc") }

// 获取值或默认值
val value = result.getOrElse { -1 }

// 链式转换
val mapped = result.flatMap { runCatching { it * 2 } }

JSON

val json = toJson(#{"name": "Nova", "version": "0.1"})
val obj = parseJson(json)

内置常量

常量
PI3.141592653589793
E2.718281828459045
TAU6.283185307179586
MAX_INT2147483647
MIN_INT-2147483648
NaN非数字

String 方法

val s = "Hello Nova"
s.length()           // 10
s.isEmpty()          // false
s.toUpperCase()      // "HELLO NOVA"
s.toLowerCase()      // "hello nova"
s.capitalize()       // "Hello nova"
s.trim()             // 去除首尾空白
s.contains("Nova")   // true
s.startsWith("He")   // true
s.indexOf("Nova")    // 6
s.replace("Nova", "World")
s.split(" ")         // ["Hello", "Nova"]
s.substring(0, 5)    // "Hello"
s.reverse()          // "avoN olleH"
s.lines()            // 按行分割
s.matches("\\w+")    // 正则匹配
s.padStart(15, '*')  // "*****Hello Nova"

List 方法

val list = [1, 2, 3, 4, 5]
list.size()                     // 5
list.first()                    // 1
list.last()                     // 5
list.contains(3)                // true
list.indexOf(3)                 // 2

// 变换
list.map { it * 2 }            // [2, 4, 6, 8, 10]
list.filter { it > 3 }         // [4, 5]
list.flatMap { [it, it * 10] } // [1, 10, 2, 20, ...]
list.distinct()                 // 去重
list.sorted()                   // 排序
list.reversed()                 // 反转
list.take(3)                    // [1, 2, 3]
list.drop(2)                    // [3, 4, 5]
list.chunked(2)                 // [[1,2], [3,4], [5]]

// 聚合
list.sum()                      // 15
list.reduce { a, b -> a + b }  // 15
list.fold(0) { acc, x -> acc + x }
list.all { it > 0 }            // true
list.any { it > 4 }            // true
list.none { it < 0 }           // true
list.joinToString(", ")         // "1, 2, 3, 4, 5"
list.groupBy { it % 2 }        // {1: [1,3,5], 0: [2,4]}

// 遍历
list.forEach { println(it) }
list.forEachIndexed { i, v -> println("$i: $v") }

枚举方法

enum Color { RED, GREEN, BLUE }

val all = Color.entries       // [RED, GREEN, BLUE](枚举条目列表)

Map 方法

val map = #{"a": 1, "b": 2, "c": 3}
map.size()              // 3
map.get("a")            // 1
map.containsKey("b")    // true
map.keys()              // ["a", "b", "c"]
map.values()            // [1, 2, 3]
map.entries()           // [("a",1), ("b",2), ("c",3)]
map.forEach { k, v -> println("$k=$v") }
map.map { k, v -> "$k:$v" }
map.filter { k, v -> v > 1 }

作用域函数

val result = value.let { it * 2 }
value.also { println(it) }
obj.run { method1(); method2() }
obj.apply { field = "value" }
value.takeIf { it > 0 }       // 满足条件返回自身,否则 null
value.takeUnless { it < 0 }   // 不满足条件返回自身