语法文档
NovaLang 完整语法参考
语法文档
NovaLang 采用类似 Kotlin 的语法风格,简洁而富有表达力。
字面量
// 整数
val a = 42
val hex = 0xFF
val bin = 0b1010
val big = 1_000_000L
// 浮点数
val pi = 3.14
val sci = 1.5e10
// 字符串
val s = "Hello, $name"
val multi = """
多行字符串
支持 ${1 + 2} 插值
"""
val raw = r"C:\Users\path" // 原始字符串,不解析转义
// 其他
val c = 'A' // 字符
val yes = true // 布尔
val nothing = null // 空值
变量声明
val name = "Nova" // 不可变
var count = 0 // 可变
val age: Int = 25 // 显式类型标注
// 解构声明
val (x, y) = Pair(1, 2)
var (a, b, c) = [10, 20, 30]
// 基于名称的解构声明(按属性名而非位置,顺序任意)
@data class User(val username: String, val email: String)
val user = User("alice", "alice@example.com")
val (mail = email, name = username) = user // mail="alice@example.com", name="alice"
// 名称解构也可用于 for 循环
for ((cost = price) in items) {
println(cost)
}
// 编译期常量
const val MAX_SIZE = 100
const val PI = 3.14159
函数
// 基本函数
fun add(a: Int, b: Int): Int {
return a + b
}
// 表达式函数体
fun square(x: Int): Int = x * x
// 默认参数
fun greet(name: String, greeting: String = "Hello"): String {
return "$greeting, $name!"
}
// 可变参数
fun sum(vararg numbers: Int): Int {
var total = 0
for (n in numbers) total += n
return total
}
// 泛型函数
fun <T> first(list: List<T>): T = list[0]
// 扩展函数
fun String.shout(): String = this.toUpperCase() + "!"
// 扩展属性
val String.lastChar get() = this[this.length() - 1]
// 中缀函数
infix fun Int.power(exp: Int): Int = pow(this, exp).toInt()
val result = 2 power 10 // 1024
类与对象
// 基本类
class Point(val x: Int, val y: Int) {
fun distance(): Double = sqrt(x * x + y * y)
}
// 继承
open class Shape {
open fun area(): Double = 0.0
}
class Circle(val radius: Double) : Shape() {
override fun area(): Double = PI * radius * radius
}
// 抽象类
abstract class Animal(val name: String) {
abstract fun sound(): String
}
// 密封类
sealed class Result {
class Ok(val value: Any) : Result()
class Err(val msg: String) : Result()
}
// 密封接口(常与 @data class / @data object 配合)
sealed interface ApiResult {
@data class Success(val data: String) : ApiResult
@data object Loading : ApiResult
@data object Error : ApiResult
}
// 接口
interface Drawable {
fun draw()
}
// Data Class
data class User(val name: String, val age: Int)
// Data Object(无数据状态,自动生成 toString 返回类名)
@data object NotFound
// 枚举
enum Color { RED, GREEN, BLUE }
// 单例对象
object Logger {
fun log(msg: String) = println("[LOG] $msg")
}
// 伴生对象
class Factory {
companion {
fun create(): Factory = Factory()
}
}
// 可见性修饰符: public(默认), private, protected, internal
控制流
// if 表达式
val result = if (x > 0) "positive" else "non-positive"
// when 表达式
val desc = when (value) {
1 -> "one"
2, 3 -> "few"
in 4..10 -> "several"
is String -> "text: $value"
else -> "other"
}
// when Guard Conditions(条件匹配 + guard 为真才进入分支)
when (animal) {
is Cat if !animal.isHungry -> "relaxed cat"
is Cat -> "hungry cat"
is Dog if animal.isPlayful -> "playful dog"
1, 2 if flag -> "small with flag"
else -> "unknown"
}
// for 循环
for (i in 1..10) { println(i) }
for (i in 0..<10 step 2) { println(i) } // 0, 2, 4, 6, 8
for ((k, v) in map) { println("$k=$v") }
// while / do-while
while (condition) { /* ... */ }
do { /* ... */ } while (condition)
// try-catch-finally
try {
riskyOperation()
} catch (e) {
println("Error: $e")
} finally {
cleanup()
}
// guard (条件守卫)
guard (x > 0) else { return }
// use (自动资源管理)
use (val file = openFile("data.txt")) {
println(file.read())
}
// break / continue 带标签
outer@ for (i in 1..10) {
for (j in 1..10) {
if (j == 5) break@outer
}
}
// Non-local break/continue(在 forEach 等 lambda 内使用)
list.forEach {
if (it == 0) continue // 跳过当前迭代
if (it == target) break // 终止整个循环
process(it)
}
// 支持 forEach、forEachIndexed、Map forEach
// 嵌套 forEach 中 break 只影响最内层
表达式与操作符
// 算术: + - * / % ++ --
// 比较: == != < > <= >= === !==
// 逻辑: && || !
// 位运算: & | ^ ~ << >> >>>
// 赋值: = += -= *= /= %= ??= ||= &&=
// 空安全
val len = name?.length() // 安全调用
val def = name ?: "default" // Elvis 操作符
val sure = name!! // 非空断言
// 类型操作
if (obj is String) { /* 智能转换 */ }
val s = obj as String // 强转
val s = obj as? String // 安全强转,失败返回 null
// 范围
val r1 = 1..10 // 闭区间 [1, 10]
val r2 = 0..<10 // 半开区间 [0, 10)
// Lambda
val double = { x -> x * 2 }
val list = [1, 2, 3].map { it * 10 }
// Lambda with Receiver(接收者函数类型)
fun buildConfig(block: Config.() -> Unit): Config {
val cfg = Config()
cfg.block() // block 内可直接访问 Config 的属性和方法
return cfg
}
val config = buildConfig {
host = "0.0.0.0" // 直接访问 Config.host
port = 8080 // 直接访问 Config.port
}
// 管道操作符
val result = "hello" |> { it.toUpperCase() } |> { "$it!" }
// 方法引用
val fn = String::toUpperCase
// 集合字面量
val list = [1, 2, 3]
val map = #{"name": "Nova", "version": "0.1"}
// 展开操作符
fun sum(a: Int, b: Int, c: Int) = a + b + c
val args = [1, 2, 3]
sum(*args)
运算符重载
class Vec(val x: Int, val y: Int) {
operator fun plus(other: Vec) = Vec(x + other.x, y + other.y)
operator fun times(n: Int) = Vec(x * n, y * n)
operator fun get(i: Int) = if (i == 0) x else y
}
val v = Vec(1, 2) + Vec(3, 4) // Vec(4, 6)
异步编程
// 异步执行
val future = async { heavyComputation() }
val result = await future
// 并行任务
val (a, b) = parallel(
{ fetchUserData() },
{ fetchOrders() }
)
// 结构化并发
coroutineScope {
val f1 = async { task1() }
val f2 = async { task2() }
awaitAll(f1, f2)
}
// 超时控制
withTimeout(5000) {
longRunningTask()
}
注解
// 使用注解
@data
class User(val name: String, val age: Int)
// 定义注解
annotation class Route(val path: String)
@Route("/api/users")
fun getUsers() { /* ... */ }