标准库参考

Aria 内置了丰富的标准库函数,按命名空间组织。调用方式为 命名空间.函数名(参数)


全局函数

无需命名空间前缀,直接调用。

函数签名说明
printprint(args...)输出内容(不换行)
printlnprintln(args...)输出内容(换行)
print("hello", "world")   // hello world
println("done")           // done\n

console — 控制台

函数签名说明
logconsole.log(args...)输出到标准输出
errorconsole.error(args...)输出到标准错误
warnconsole.warn(args...)输出警告(同 error)
console.log("info message")
console.error("something went wrong")

math — 数学

常量

函数说明
math.PI()圆周率 π
math.pi()圆周率 π(小写别名,零参调用)
math.E()自然常数 e

基础运算

函数签名说明
absmath.abs(x)绝对值
floormath.floor(x)向下取整
ceilmath.ceil(x)向上取整
roundmath.round(x)四舍五入
sqrtmath.sqrt(x)平方根
cbrtmath.cbrt(x)立方根
powmath.pow(x, y)x 的 y 次方
minmath.min(a, b)最小值
maxmath.max(a, b)最大值
randommath.random()[0, 1) 随机数
signummath.signum(x)符号函数
rintmath.rint(x)最接近的整数(银行家舍入)
hypotmath.hypot(a, b)斜边长度 √(a²+b²)

三角函数

函数签名说明
sinmath.sin(x)正弦
cosmath.cos(x)余弦
tanmath.tan(x)正切
asinmath.asin(x)反正弦
acosmath.acos(x)反余弦
atanmath.atan(x)反正切
atan2math.atan2(y, x)二参数反正切

双曲函数

函数签名说明
sinhmath.sinh(x)双曲正弦
coshmath.cosh(x)双曲余弦
tanhmath.tanh(x)双曲正切

指数与对数

函数签名说明
logmath.log(x)自然对数
log10math.log10(x)以 10 为底的对数
log1pmath.log1p(x)ln(1+x),小值精度更高
expmath.exp(x)e^x
expm1math.expm1(x)e^x - 1,小值精度更高

角度转换

函数签名说明
toDegreesmath.toDegrees(rad)弧度 → 角度
toRadiansmath.toRadians(deg)角度 → 弧度

浮点操作

函数签名说明
ulpmath.ulp(x)最小精度单位
copySignmath.copySign(mag, sign)复制符号
scalbmath.scalb(x, exp)x × 2^exp
nextUpmath.nextUp(x)下一个浮点数(正方向)
nextDownmath.nextDown(x)下一个浮点数(负方向)
nextAftermath.nextAfter(a, b)a 朝 b 方向的下一个浮点数
IEEEremaindermath.IEEEremainder(a, b)IEEE 余数
getExponentmath.getExponent(x)获取指数部分
r = math.sqrt(16)          // 4.0
angle = math.atan2(1, 1)   // 0.7853... (π/4)
d = math.toDegrees(angle)  // 45.0

type — 类型

函数签名说明
typeoftype.typeof(value)返回类型名称字符串
isNonetype.isNone(value)是否为 none
isNumbertype.isNumber(value)是否为数字
isStringtype.isString(value)是否为字符串
isListtype.isList(value)是否为列表
isMaptype.isMap(value)是否为字典
isFunctiontype.isFunction(value)是否为函数
toNumbertype.toNumber(value)转换为数字
toStringtype.toString(value)转换为字符串
toBooleantype.toBoolean(value)转换为布尔值

类型名称对照:nonenumberbooleanstringobjectstoreclassfunctionlistmap

t = type.typeof(42)       // "number"
ok = type.isString("hi")  // true
n = type.toNumber("3.14") // 3.14

regex — 正则表达式

函数签名说明
matchregex.match(pattern, str)返回第一个匹配 [fullMatch, group1, ...],无匹配返回 none
matchAllregex.matchAll(pattern, str)返回所有匹配的列表
testregex.test(pattern, str)是否匹配
replaceregex.replace(pattern, str, replacement)替换所有匹配
replaceFirstregex.replaceFirst(pattern, str, replacement)替换第一个匹配
splitregex.split(pattern, str)按正则分割
ok = regex.test("\\d+", "abc123")  // true
m = regex.match("(\\w+)@(\\w+)", "user@host")
// m = ["user@host", "user", "host"]

crypto — 加密/编码

函数签名说明
md5crypto.md5(str)MD5 哈希
sha1crypto.sha1(str)SHA-1 哈希
sha256crypto.sha256(str)SHA-256 哈希
sha512crypto.sha512(str)SHA-512 哈希
base64Encodecrypto.base64Encode(str)Base64 编码
base64Decodecrypto.base64Decode(str)Base64 解码
uuidcrypto.uuid()生成随机 UUID
hashCodecrypto.hashCode(str)Java hashCode
hash = crypto.sha256("hello")
encoded = crypto.base64Encode("hello world")
id = crypto.uuid()  // "550e8400-e29b-..."

datetime — 日期时间

内部使用 epoch 毫秒(数字)表示时间点。

函数签名说明
nowdatetime.now()当前时间戳(毫秒)
timestampdatetime.timestamp()当前时间戳(秒,浮点)
formatdatetime.format(millis, pattern?)格式化时间,默认 yyyy-MM-dd HH:mm:ss
parsedatetime.parse(str, pattern?)解析时间字符串为毫秒
diffdatetime.diff(millis1, millis2, unit?)时间差,unit: millis/seconds/minutes/hours/days
yeardatetime.year(millis)获取年份
monthdatetime.month(millis)获取月份
daydatetime.day(millis)获取日
hourdatetime.hour(millis)获取小时
minutedatetime.minute(millis)获取分钟
seconddatetime.second(millis)获取秒
dayOfWeekdatetime.dayOfWeek(millis)星期几(1=周一,7=周日)
addDaysdatetime.addDays(millis, n)加 n 天
addHoursdatetime.addHours(millis, n)加 n 小时
addMinutesdatetime.addMinutes(millis, n)加 n 分钟
addSecondsdatetime.addSeconds(millis, n)加 n 秒
now = datetime.now()
str = datetime.format(now)  // "2026-01-15 14:30:00"
tomorrow = datetime.addDays(now, 1)
diff = datetime.diff(now, tomorrow, "hours")  // 24.0

scheduler — 定时调度

函数签名说明
delayscheduler.delay(millis, fn)延迟执行,返回 taskId
intervalscheduler.interval(millis, fn)周期执行,返回 taskId
cancelscheduler.cancel(taskId)取消任务,返回是否成功
cancelAllscheduler.cancelAll()取消所有任务
id = scheduler.delay(1000, -> {
    println("1 秒后执行")
})

timerId = scheduler.interval(500, -> {
    println("每 500ms 执行一次")
})
scheduler.cancel(timerId)

template — 模板引擎

支持 {key} 占位符替换,{{}} 为转义。

函数签名说明
rendertemplate.render(template, data)渲染模板,data 为 Map
result = template.render("Hello, {name}! Age: {age}", {
    "name": "Alice",
    "age": 25
})
// result = "Hello, Alice! Age: 25.0"

fs — 文件系统

函数签名说明
readfs.read(path)读取文件内容(字符串)
writefs.write(path, content)写入文件
existsfs.exists(path)文件是否存在
listfs.list(dir)列出目录下的文件名
mkdirfs.mkdir(path)创建目录(含父目录)
deletefs.delete(path)删除文件
copyfs.copy(src, dst)复制文件
appendfs.append(path, content)追加内容到文件末尾
readLinesfs.readLines(path)按行读取文件,返回字符串列表
infofs.info(path)文件信息,返回 {size, isDir, modified, created}
fs.write("test.txt", "hello world")
content = fs.read("test.txt")  // "hello world"
files = fs.list(".")
info = fs.info("test.txt")     // {size: 11, isDir: false, ...}

net — 网络/HTTP

函数签名说明
getnet.get(url, headers?)HTTP GET
postnet.post(url, body, headers?)HTTP POST
putnet.put(url, body, headers?)HTTP PUT
deletenet.delete(url, headers?)HTTP DELETE
requestnet.request(options)完整控制的 HTTP 请求
asyncGetnet.asyncGet(url, [headers,] callback)异步 GET
asyncPostnet.asyncPost(url, body, [headers,] callback)异步 POST

所有同步请求返回 {status, body, headers} 格式的 Map。

net.request 的 options 格式:{url, method, body, headers, timeout}

异步回调签名:callback(error, response),error 为 none 表示成功。

resp = net.get("https://api.example.com/data")
println(resp.status)  // 200.0
println(resp.body)

resp2 = net.post("https://api.example.com/data", '{"key":"value"}', {
    "Content-Type": "application/json"
})

net.asyncGet("https://api.example.com/data", -> {
    println(args[1].body)
})

event — 事件总线

函数签名说明
onevent.on(eventName, handler)注册事件监听器
emitevent.emit(eventName, args...)触发事件
offevent.off(eventName)移除事件的所有监听器
event.on("user.login", -> {
    println("User logged in: " + args[0])
})
event.emit("user.login", "Alice")
event.off("user.login")

json — JSON 序列化

函数签名说明
parsejson.parse(str)JSON 字符串 → Aria 值
stringifyjson.stringify(value, pretty?)Aria 值 → JSON 字符串,pretty=true 格式化输出
obj = json.parse('{"name": "Alice", "age": 25}')
println(obj.name)  // "Alice"

str = json.stringify({"key": "value"}, true)

serial — 二进制序列化

函数签名说明
encodeserial.encode(value)将值编码为二进制(byte[])
decodeserial.decode(bytes)从二进制解码为值

支持的类型:none、number、boolean、string、list、map。

data = {"name": "Alice", "scores": [90, 85, 92]}
bytes = serial.encode(data)
restored = serial.decode(bytes)

db — 数据库

db 命名空间由独立模块 aria-db 提供,需在 classpath 中引入并注册(见「嵌入」文档的依赖配置)。核心引擎默认不包含 db

支持 SQLite、H2、MySQL。

函数签名说明
connectdb.connect(type, path, [user, password])连接数据库,返回连接对象
tabledb.table(conn, name, columns)创建表,columns 为 {列名: 类型}
createTabledb.createTable(conn, name, columns)同 table
dropTabledb.dropTable(conn, name)删除表
insertdb.insert(conn, table, data)插入数据,data 为 Map
selectdb.select(conn, table, where?)查询,where 为 Map 条件
updatedb.update(conn, table, data, where?)更新数据
deletedb.delete(conn, table, where?)删除数据
executedb.execute(conn, sql, params...)执行原始 SQL
transactiondb.transaction(conn, fn)事务执行,异常自动回滚
closedb.close(conn)关闭连接
conn = db.connect("sqlite", "test.db")
db.table(conn, "users", {"id": "INTEGER PRIMARY KEY", "name": "TEXT", "age": "INTEGER"})

db.insert(conn, "users", {"name": "Alice", "age": 25})
db.insert(conn, "users", {"name": "Bob", "age": 30})

rows = db.select(conn, "users", {"name": "Alice"})
println(rows)  // [{id: 1.0, name: "Alice", age: 25.0}]

db.update(conn, "users", {"age": 26}, {"name": "Alice"})
db.delete(conn, "users", {"name": "Bob"})

db.transaction(conn, -> {
    db.insert(conn, "users", {"name": "Charlie", "age": 35})
    db.insert(conn, "users", {"name": "Diana", "age": 28})
})

db.close(conn)

对象方法

以下方法通过 .方法名() 在对象上调用。

字符串方法

方法签名说明
lengthstr.length()字符串长度
substringstr.substring(start, end?)子串
replacestr.replace(target, replacement)替换所有匹配(字面量);只给 1 个参数时返回原串
replaceAllstr.replaceAll(regex, replacement)正则替换所有
replaceFirststr.replaceFirst(regex, replacement)正则替换第一个
splitstr.split(delimiter[, limit])按正则分割为列表;默认(无 limit)丢弃尾部空串
trimstr.trim()去除首尾空白
startsWithstr.startsWith(prefix[, offset])是否以 prefix 开头(可从 offset 位置起判断)
endsWithstr.endsWith(suffix)是否以 suffix 结尾
containsstr.contains(sub)是否包含子串
indexOfstr.indexOf(sub[, from])子串首次出现位置,-1 表示未找到(可从 from 起查)
lastIndexOfstr.lastIndexOf(sub[, from])子串最后出现位置(可从 from 向前查)
toUpperCasestr.toUpperCase()转大写(Locale.ROOT,不受系统语言影响)
toLowerCasestr.toLowerCase()转小写(Locale.ROOT)
charAtstr.charAt(index)获取指定位置字符
equalsstr.equals(other)严格相等比较
equalsIgnoreCasestr.equalsIgnoreCase(other)忽略大小写比较
isEmptystr.isEmpty()是否为空串
repeatstr.repeat(count)重复字符串 count 次
s = "Hello, World!"
println(s.length())        // 13.0
println(s.substring(0, 5)) // "Hello"
println(s.toUpperCase())   // "HELLO, WORLD!"
parts = s.split(", ")      // ["Hello", "World!"]

println('a,b,,'.split(',').size())    // 2.0(尾部空串被丢弃)
println('a,b,c'.split(',', 2)[1])     // "b,c"(limit 限制段数)
println('abcabc'.startsWith('b', 1))  // true
println('abcabc'.indexOf('a', 1))     // 3.0

列表方法

基础操作

方法签名说明
addlist.add(item)追加元素到末尾
addlist.add(index, item)插入元素到指定索引
removelist.remove(value)删除首个相等元素(跨类型数值相等),返回 boolean
removeIndexlist.removeIndex(index)索引删除,返回被删元素;上越界返回 none,负索引抛错
getlist.get(index)获取指定索引元素;上越界返回 none,负索引抛错
setlist.set(index, value)设置指定索引元素,返回旧元素;越界不写入
sizelist.size()列表长度
containslist.contains(item)是否包含元素(跨类型数值相等:contains('2') 匹配 2
containsAlllist.containsAll(other)是否包含另一列表的全部元素(此方法做跨类型匹配)
indexOflist.indexOf(item)元素首次出现位置(跨类型数值相等),-1 未找到
lastIndexOflist.lastIndexOf(item)元素最后出现位置(跨类型数值相等)
sortlist.sort()按数值排序(原地)
reverselist.reverse()反转(原地)
clearlist.clear()清空
isEmptylist.isEmpty()是否为空
subListlist.subList(from, to)子列表 [from, to);要求 fromto小于 size,否则返回 none
addAlllist.addAll(other)追加另一列表全部元素,返回 boolean;非列表参数按单元素处理
removeAlllist.removeAll(other)移除另一列表中的所有元素,返回 boolean;非列表参数按单元素处理
retainAlllist.retainAll(other)仅保留另一列表中出现的元素(跨类型数值相等),返回是否发生变化
joinlist.join(separator?)拼接为字符串,默认 ,

高阶函数

方法签名说明
maplist.map(fn)映射,fn(item, index) → 新列表
filterlist.filter(fn)过滤,fn(item, index) → 新列表
reducelist.reduce(fn, initial?)累积,fn(acc, item, index)
forEachlist.forEach(fn)遍历,fn(item, index)
findlist.find(fn)查找第一个满足条件的元素
findIndexlist.findIndex(fn)查找第一个满足条件的索引
everylist.every(fn)是否所有元素都满足条件
somelist.some(fn)是否至少一个元素满足条件
flatMaplist.flatMap(fn)map + flatten
sortBylist.sortBy(fn)按 fn 返回值排序(原地)
nums = [3, 1, 4, 1, 5]
doubled = nums.map(-> { return args[0] * 2 })     // [6, 2, 8, 2, 10]
evens = nums.filter(-> { return args[0] % 2 == 0 }) // [4]
sum = nums.reduce(-> { return args[0] + args[1] }, 0) // 14
found = nums.find(-> { return args[0] > 3 })       // 4
println(nums.join("-"))  // "3.0-1.0-4.0-1.0-5.0"

字典方法

基础操作

方法签名说明
putmap.put(key, value)设置键值对,返回该键的旧值(无则 none
getmap.get(key)获取值
removemap.remove(key)移除键值对,返回被移除的值
sizemap.size()键值对数量
keysmap.keys()所有键的列表
valuesmap.values()所有值的列表
entriesmap.entries()所有键值对 [[key, value], ...]
containsKeymap.containsKey(key)是否包含键
containsValuemap.containsValue(value)是否包含值
clearmap.clear()清空
isEmptymap.isEmpty()是否为空
putAllmap.putAll(otherMap)合并另一个字典(接受任意 map;非 map 参数静默忽略)
putIfAbsentmap.putIfAbsent(key, value)键不存在时设置并返回 none;已存在时返回旧值(宿主包装形式)
getOrDefaultmap.getOrDefault(key, default)获取值,不存在返回默认值

高阶函数

方法签名说明
forEachmap.forEach(fn)遍历,fn(key, value)
filtermap.filter(fn)过滤,fn(key, value) → 新字典
mapValuesmap.mapValues(fn)映射值,fn(value, key) → 新字典
m = {"name": "Alice", "age": 25}
println(m.keys())    // [name, age]
println(m.size())    // 2.0

m.forEach(-> {
    println(args[0] + " = " + args[1])
})

filtered = m.filter(-> { return args[0] != "age" })

数字方法

方法签名说明
toIntnum.toInt()转为整数(截断小数)
toFixednum.toFixed(digits)保留指定小数位(返回字符串)
isNaNnum.isNaN()是否为 NaN
isInfinitenum.isInfinite()是否为无穷大
roundnum.round(places)四舍五入到指定小数位
absnum.abs()绝对值
ceilnum.ceil()向上取整
floornum.floor()向下取整
p = 3.14159
println(p.toFixed(2))  // "3.14"
println(p.round(3))    // 3.142
println(p.toInt())     // 3.0

UUID

通过构造器创建 UUID 对象:

用法说明
id = UUID()生成随机 UUID
id = UUID('550e8400-e29b-41d4-a716-446655440000')从字符串解析 UUID

非法字符串不抛异常,回退为随机 UUID:UUID('not-a-uuid') 得到一个随机 UUID 对象。

UUID 对象方法:

方法说明
getMostSignificantBits高 64 位(数字)
getLeastSignificantBits低 64 位(数字)
versionUUID 版本号(如 4)
variantUUID variant(一般为 2)
id = UUID()
print(id)  // 550e8400-e29b-41d4-a716-446655440000

u = UUID('550e8400-e29b-41d4-a716-446655440000')
print(u.version())  // 4.0

Range

通过构造器创建范围对象,支持可选的步长参数:

用法说明
Range(start, end)创建双端闭区间 [start, end],步长默认为 1
Range(start, end, step)创建范围,指定步长
start..end字面量简写,等价 Range(start, end)

规则:

  • Range 是双端闭区间:Range(1, 10) 含 1 也含 10;
  • start > end 且未显式给步长时是空区间(不自动倒序);倒序需 Range(10, 1, -1)
  • 参数少于 2 个时按 (0, 0) 处理(Range()Range(5) 都只含 0);
  • ~~ 的右值只认 Range(见运算符)。

start..endRange(start, end) 完全等价,可直接用于 for-in~~

for (i in 3..7) {
    print(i)  // 3.0, 4.0, 5.0, 6.0, 7.0(含 7)
}
r = Range(1, 10)
for (i in r) {
    print(i)  // 1.0, 2.0, 3.0, ..., 10.0
}

r2 = Range(0, 10, 2)
for (i in r2) {
    print(i)  // 0.0, 2.0, 4.0, 6.0, 8.0, 10.0
}

动画缓动函数

动画缓动对象位于独立模块 aria-animations,需要将其加入 classpath 后自动注册。共 24 个缓动对象:

对象说明
Back(duration)回弹缓动
Bezier(...)贝塞尔曲线
Blink(...)闪烁效果
Bounce(duration)弹跳缓动
Breathe(...)呼吸效果
CircX(duration)圆形缓动 X
CircY(duration)圆形缓动 Y
Elastic(duration)弹性缓动
Expo(duration)指数缓动
Fade(...)淡入淡出
Lerp(from, to)线性插值
Pulse(...)脉冲效果
Q2(duration)二次缓动
Q3(duration)三次缓动
Q4(duration)四次缓动
Q5(duration)五次缓动
Shake(...)抖动效果
Sine(duration)正弦缓动
Slide(...)滑动效果
Smooth(duration)平滑缓动
Spring(...)弹簧效果
Swing(duration)摆动缓动
TwoLerp(...)双线性插值
Wave(...)波浪效果