语言导览

这份导览通过一组可运行的小程序介绍 Scoop 的主要特性。每段代码都附有实际运行输出,你可以把它保存为 .scoop 文件,用 scoop run 运行。如果你熟悉 Kotlin,大部分语法会很眼熟;差异集中整理在对比 Kotlin一页。

基础

程序从 fun main() 开始。val 声明不可重新赋值的绑定,var 声明可变变量;类型可以省略,由编译器推断。if、when 和 try 都是表达式。

basics.scoop
fun fib(n: Int): Long {
    var a = 0L
    var b = 1L
    for (i in 0 until n) {
        val next = a + b
        a = b
        b = next
    }
    return a
}

fun classify(n: Int): String = if (n % 2 == 0) "even" else "odd"

fun main() {
    val name = "Scoop"
    var count = 3
    count += 1
    println(f"Hello, ${name}! count=${count}")
    println(f"fib(50) = ${fib(50)}")
    for (n in 1..3) {
        println(f"${n} is ${classify(n)}")
    }
    val text = """raw string: $name is literal"""
    println(text)
}
Hello, Scoop! count=4 fib(50) = 12586269025 1 is odd 2 is even 3 is odd raw string: $name is literal
  • 字符串插值只在 f-string 中生效:f"…${expr}…",花括号不能省略;普通字符串里的 $ 就是普通字符。
  • """…""" 与 f"""…""" 是保留换行的 raw 字符串。
  • 1..3 是闭区间,0 until n 是半开区间。

数值类型

整数有八种定宽表示:Int8/Int16/Int/Long 与对应的无符号 UInt8/UInt16/UInt/ULong,Int 在所有目标上固定 32 位,Long 固定 64 位;Byte、Short、Int64 等是透明别名。浮点数有 Float 与 Double。

  • 字面量:42、42L、42u、42uL、0xFF、0b1010、1_000_000;
  • 不同宽度或符号的整数之间不做隐式提升,需要显式调用 toLong()、toUInt() 等;
  • 算术溢出按二进制补码回绕,不抛异常;整数除零抛出 ArithmeticException;
  • 集合长度和下标使用 Long,例如 names[0L]、text.charLength。

struct:值类型

struct 是不可变的聚合值类型:没有 identity,按值复制,作为字段或数组元素时内联存储。字段在主构造函数中用 val 声明,可以带默认值,构造时可以使用命名参数。

structs.scoop
struct Point(val x: Int, val y: Int) : ToString {
    fun dist2(): Int = x * x + y * y
    public override fun toString(): String = f"(${x}, ${y})"
}

struct Config(val host: String, val port: Int = 8080, val debug: Boolean = false)

fun main() {
    val p = Point(3, 4)
    val q = p.{ y: 10 }
    println(f"p=${p} q=${q} |p|^2=${p.dist2()}")
    println(p == Point(3, 4))

    val (x, y) = p
    println(x + y)

    val config = Config("localhost", debug = true)
    val Config { host, port, .. } = config
    println(f"${host}:${port}")

    val pair = (1, "one")
    val (num, word) = pair
    println(f"${num} -> ${word}, ${pair._2}")
}
p=(3, 4) q=(3, 10) |p|^2=25 true 7 localhost:8080 1 -> one, one
  • 副本更新 p.{ y: 10 } 基于已有值创建修改了部分字段的新值,原值不变;
  • struct 自动获得逐字段的结构相等 ==;值类型上使用 === 是编译错误;
  • 解构可以按位置 val (x, y) = p,也可以按字段名 val Config { host, port, .. } = config,.. 忽略其余字段;
  • tuple 是匿名的积类型:(1, "one"),通过 ._1、._2 或解构访问;() 就是 Unit,1 元 tuple 写作 (e,);
  • ToString、Hash 不会自动派生,需要像上面那样显式实现。

enum 与模式匹配

Scoop 的 enum 是带载荷的代数数据类型(类似 Rust)。变体可以没有载荷、携带位置参数,或携带命名字段。when 中以 case 开头的分支使用模式语义,可以嵌套匹配 enum、tuple 和 struct,并用 if 添加 guard。

enums.scoop
enum Shape {
    Circle(Double),
    Rect { width: Double, height: Double },
    Empty
}

fun area(shape: Shape): Double = when (shape) {
    case Circle(val r) -> 3.14159 * r * r
    case Rect { val width, val height } -> width * height
    case Empty -> 0.0
}

fun describe(value: (Int, Shape)): String = when (value) {
    case (0, _) -> "zero-th"
    case (val n, Circle(val r)) if r > 10.0 -> f"#${n}: big circle"
    case (val n, Circle(_)) -> f"#${n}: circle"
    case (val n, _) -> f"#${n}: other"
}

enum Status: Int {
    Ok = 200,
    NotFound = 404
}

fun main() {
    val shapes = [Shape.Circle(1.0), Shape.Rect(width = 2.0, height = 3.0), Shape.Empty]
    for (s in shapes) println(area(s))
    println(describe((1, Shape.Circle(20.0))))
    println(describe((2, Shape.Empty)))
    val code: Int = Status.NotFound
    println(code)
}
3.14159 6.0 0.0 #1: big circle #2: other 404
  • 在 case 中,变体名可以省略 Shape. 前缀,由 subject 的类型解析;
  • 模式中的绑定必须显式写 val,例如 Circle(val r)、Rect { val width, val height };不带 val 的裸名称只匹配 enum 变体;
  • 含 case 的 when 必须穷尽,否则编译器会报错并给出一个未覆盖的示例;带 guard 的分支不计入覆盖;
  • enum Status: Int { … } 声明整型枚举:每个变体有显式数值,可以按值上转为 Int,但整数不能隐式转回枚举;
  • 变体不是类型,不能用于 is 检查或作为变量类型,提取载荷一律通过 when。

Option:没有 null

Scoop 没有运行期 null。T? 只是核心库 enum Option<T> { Some(T), None } 的语法糖,Kotlin 的空安全运算符照常使用:

options.scoop
struct User(val name: String, val email: String?)

fun find(users: Array<User>, name: String): User? {
    for (u in users) {
        if (u.name == name) return Some(u)
    }
    return None
}

fun main() {
    val users = [User("ada", Some("[email protected]")), User("lin", None)]
    // `?.` does not flatten: the result is Option<Option<String>>
    val email: String?? = find(users, "ada")?.email
    println(email == Some(Some("[email protected]")))
    val domain: String = when (val e = find(users, "lin")) {
        case Some(User { email: Some(val addr), .. }) -> addr
        case Some(_) -> "no email"
        case None -> "no user"
    }
    println(domain)
    println(find(users, "bob")?.name ?: "anonymous")
    val nested: Int?? = Some(None)
    println(nested == None)
}
true no email anonymous false
  • a?.b:a 为 Some(v) 时得到 Some(v.b),否则为 None;
  • a ?: b:取 Some 的载荷,否则求值 b(可以是 return 或 throw);
  • a!!:取载荷,None 时抛出 UnwrapException;
  • 可空是逐层的:T?? 是 Option<Option<T>>,Some(None) 与 None 可以区分;安全调用不会展平结果;
  • Option 是普通 enum,可以直接在 when 里深度匹配,例如 case Some(User { email: Some(val addr), .. })。

类、接口与对象

类、接口、object 和 companion object 是引用类型,语法与 Kotlin 一致。类和方法默认 final,需要 open 才能被继承或覆写;接口方法可以有默认实现;扩展函数为已有类型添加方法。

classes.scoop
import scoop.text.*

interface Animal {
    val name: String
    fun sound(): String
    fun greet(): String = f"${name} says ${sound()}"
}

open class Pet(override val name: String) : Animal {
    override fun sound(): String = "..."
}

class Dog(name: String) : Pet(name) {
    override fun sound(): String = "woof"
}

class Counter {
    var value: Int = 0

    fun increment() {
        value += 1
    }

    companion object {
        fun startingAt(n: Int): Counter {
            val c = Counter()
            for (i in 0 until n) c.increment()
            return c
        }
    }
}

object Registry {
    val names = ArrayList<String>()
}

fun String.shout(): String = this.uppercaseAscii() + "!"

fun main() {
    val animals: Array<Animal> = [Dog("Rex") as Animal, Pet("Tom") as Animal]
    for (a in animals) println(a.greet())

    val c = Counter.startingAt(2)
    c.increment()
    println(c.value)

    Registry.names.add("scoop")
    println(Registry.names.size)
    println("hello".shout())
}
Rex says woof Tom says ... 3 1 HELLO!
  • 值类型(struct / enum)也可以实现接口;转为接口或 Any 时自动装箱;
  • 引用类型的 === 比较对象 identity;== 只决议静态类型上可见的 operator fun equals,不存在 Any.equals 回退;
  • 默认可见性是 internal(Cone 内可见);覆写 public 接口成员(如 ToString.toString)时需要写 public override;
  • sealed class / sealed interface 限定直接子类型,配合 when 做穷尽检查(见运算符一节的例子)。

泛型

函数、class、struct、enum 和 interface 都可以有类型参数。泛型采用单态化:每组具体类型实参生成一份专门代码,没有类型擦除,也不需要 reified。类型参数用上界约束能力,例如 T : Compare<T> 允许使用比较运算符。

generics.scoop
struct Box<T>(val value: T) {
    fun <R> map(transform: (T) -> R): Box<R> = Box(transform(value))
}

fun <T : Compare<T>> maxOf(items: Array<T>): T {
    var best = items[0L]
    for (item in items) {
        if (item > best) best = item
    }
    return best
}

fun <T : ToString> joinAll(items: Array<T>, sep: String): String {
    val sb = StringBuilder()
    var first = true
    for (item in items) {
        if (!first) sb.append(sep)
        sb.append(item)
        first = false
    }
    return sb.toString()
}

fun main() {
    val b = Box(21).map { it * 2 }
    println(b.value)
    println(maxOf([3, 9, 4]))
    println(maxOf(["pear", "apple", "zoo"]))
    println(joinAll([1, 2, 3], " + "))
}
42 9 zoo 1 + 2 + 3
  • 所有类型参数都是不变的:没有 in/out 型变和 * 投影,Box<String> 不是 Box<Any> 的子类型;
  • 调用处可以显式写类型实参,也可以用 _ 只写一部分:convert<Int, _>(value);
  • where 子句、负向约束与成员要求见参考文档的泛型一章,条件接口实现见类、接口与对象。

函数值与集合

lambda 写作 { x -> body },单参数可以用 it;最后一个函数参数可以写成尾随 lambda。scoop.collections 提供 List、HashMap、LinkedHashMap、TreeMap 等集合以及 filter/map/sorted 等常用操作。

lambdas.scoop
import scoop.collections.*
import scoop.text.*

fun repeat(times: Int, action: (Int) -> Unit) {
    for (i in 0 until times) action(i)
}

class Cell(var value: Int)

fun makeCounter(): () -> Int {
    // closures capture by value and cannot capture a `var`;
    // share mutable state through an explicit reference object
    val cell = Cell(0)
    return {
        cell.value += 1
        cell.value
    }
}

fun main() {
    repeat(2) { i -> println(f"tick ${i}") }

    val next = makeCounter()
    next()
    println(next())

    val words = listOf<String>("kotlin", "scoop", "rust", "swift")
    val result = words
        .filter { it.charLength > 4L }
        .map { it.uppercaseAscii() }
        .sorted()
    println(result.joinToString(", "))

    val lengths = HashMap<String, Long>()
    for (w in words) lengths[w] = w.charLength
    println(lengths["scoop"] ?: 0L)
}
tick 0 tick 1 2 KOTLIN, SCOOP, SWIFT 5
闭包不能捕获 var

Scoop 的闭包在创建时按值捕获环境,只允许捕获 val、参数和 this,读写外层 var 都是编译错误。需要在多个闭包之间共享可变状态时,显式捕获一个引用对象(如上例的 Cell)。

还可以使用 fun(x: Int): Int { … } 匿名函数、::name 函数引用、默认参数、命名参数和 vararg。

运算符与 sealed 层级

用 operator fun 重载运算符(plus、times、get、invoke、compareTo 等),infix fun 支持中缀调用。下面的例子同时展示了 struct 实现 sealed interface,并通过 is 分支做穷尽匹配和 smart cast:

ops.scoop
struct Vec2(val x: Double, val y: Double) : ToString {
    operator fun plus(other: Vec2): Vec2 = Vec2(x + other.x, y + other.y)
    operator fun times(k: Double): Vec2 = Vec2(x * k, y * k)
    public override fun toString(): String = f"Vec2(${x}, ${y})"
}

sealed interface Expr {}
struct Num(val value: Int) : Expr
struct Add(val left: Expr, val right: Expr) : Expr
struct Mul(val left: Expr, val right: Expr) : Expr

fun eval(e: Expr): Int = when (e) {
    is Num -> e.value
    is Add -> eval(e.left) + eval(e.right)
    is Mul -> eval(e.left) * eval(e.right)
}

fun main() {
    println((Vec2(1.0, 2.0) + Vec2(0.5, 0.5)) * 2.0)
    println(eval(Add(Num(2), Mul(Num(3), Num(4)))))
}
Vec2(3.0, 5.0) 14

异常

try/catch/finally 与 throw 和 Kotlin 一致,try 也是表达式。异常类继承自 Exception,消息是 String?。

errors.scoop
import scoop.text.*

class ParseError(message: String) : Exception(Some(message))

fun parsePort(text: String): Int {
    val n = text.toIntOrNone() ?: throw ParseError(f"not a number: ${text}")
    if (n < 1 || n > 65535) throw ParseError(f"out of range: ${n}")
    return n
}

fun main() {
    for (input in ["8080", "http", "70000"]) {
        val result = try {
            f"port ${parsePort(input)}"
        } catch (e: ParseError) {
            f"error: ${e.message ?: "?"}"
        } finally {
            println(f"checked ${input}")
        }
        println(result)
    }
}
checked 8080 port 8080 checked http error: not a number: http checked 70000 error: out of range: 70000

标准库的命名约定:可能失败的解析/查找提供抛异常版本与返回 Option 的 …OrNone 版本,例如 toInt() / toIntOrNone()。

协程与异步 I/O

Scoop 支持 suspend 函数与挂起 lambda suspend { … }。核心库提供协程原语和结构化并发(Job、Deferred、作用域取消);scoop.asyncio 的 PlatformEventLoop 提供定时器、TCP/UDP 与文件 I/O,macOS 后端使用 libdispatch,Linux 后端使用 io_uring,Windows 后端使用 IOCP:

coroutines.scoop
//! dep: scoop:scoop.asyncio:0.1.0

import scoop.asyncio.*
import scoop.time.Duration

suspend fun fetch(loop: EventLoop, id: Int, delayMs: Long): String {
    loop.sleep(Duration.milliseconds(delayMs))
    return f"result #${id}"
}

fun main() {
    val loop = eventLoop()
    loop.run suspend {
        val a = async<String> suspend { fetch(loop, 1, 30L) }
        val b = async<String> suspend { fetch(loop, 2, 10L) }
        println(a.await())
        println(b.await())
    }
}
result #1 result #2
  • scope.async 启动返回值的任务,scope.launch 启动不返回值的任务,await() / join() 等待完成;
  • 任务树是结构化的:父作用域结束前等待所有子任务。取消是协作式的,由任务检查或支持取消的挂起操作观察,异常退出时 finally 照常执行;不会抢占正在执行的普通代码;
  • PlatformEventLoop 只运行一次,不能嵌套启动或在结束后复用。Linux 后端要求内核 6.1 及所需 io_uring 能力;详见平台与异步 I/O;
  • Scoop 支持多线程,但不在类型系统中保证无数据竞争;跨线程共享数据需要使用原子类型(Atomic*,带显式内存序)或同步原语。

确定性资源管理

托管对象由 GC 回收,但文件、套接字、正则引擎等原生资源需要确定性释放。同步 I/O 和具有关闭语义的对象实现 Closeable.close(),用 use 在正文正常或异常退出时关闭;需要挂起关闭的对象实现 AsyncCloseable,使用 useAsync:

regex.scoop
//! dep: scoop:scoop.regex:0.1.0

import scoop.regex.*

fun main() {
    Regex("""(?<key>[a-z]+)=(?<value>[^;]+)""").use { pattern ->
        for (match in pattern.findAll("name=Scoop;target=native")) {
            println(f"${match.groups["key"]!!.value}: ${match.groups["value"]!!.value}")
        }
    }
    Regex("""[0-9]{4}-[0-9]{2}-[0-9]{2}""").use { pattern ->
        println(pattern.matches("2026-10-24"))
        println(pattern.matches("date=2026-10-24"))
    }
}
name: Scoop target: native true false

Closeable 继承 Disposable,默认 dispose() 转调 close(),因此复用同一套 use。取消登记、锁、线程等一般资源仍使用 Disposable.dispose()。如果正文和清理都失败,use/useAsync 用 ResourceUseException 保留两个错误。

直接持有原生资源的 final class 还可以声明 release { … },在对象被 GC 回收时尽力清理。它不保证执行时间或程序退出时执行;只能使用满足 release-safe 规则的 GC-free 操作和 helper,不能分配托管对象、挂起或通过原生调用回调 Scoop。确定性释放依靠显式 close、use 或 useAsync,不能用 @NoGC 或 release 替代:

release.scoop
@Extern(name = "malloc")
fun nativeMalloc(size: ULong): Ptr<Unit>

@Extern(name = "free")
fun nativeFree(address: Ptr<Unit>)

final class NativeOwner public constructor(private var handle: Option<Ptr<Unit>>): Closeable {
    public override fun close() {
        val owned = handle
        handle = None
        when (owned) {
            case Some(val value) -> @Unsafe
            {
                nativeFree(value)
            }
            case None -> {}
        }
    }

    release {
        when (handle) {
            case Some(val value) -> @Unsafe
            {
                nativeFree(value)
            }
            case None -> {}
        }
    }
}

fun main() {
    var p: Ptr<Unit>? = None
    @Unsafe
    {
        p = Some(nativeMalloc(64uL))
    }
    val owner = NativeOwner(p)
    owner.use { println("using native resource") }
    println("closed")
}
using native resource closed

C FFI

@Extern 把没有函数体的顶层函数绑定到原生符号。C ABI 的 extern 是 unsafe 函数,只能在 @Unsafe 上下文中调用;签名上只能出现 C 兼容(GC-free)的类型。

ffi.scoop
// Bind C functions from the default native namespace (libc)
@Extern(name = "abs")
fun cAbs(value: Int): Int

@Extern(name = "getpid")
fun cGetPid(): Int

fun main() {
    // C ABI externs are unsafe and must be called from an unsafe context
    @Unsafe {
        println(cAbs(-42))
        println(cGetPid() > 0)
    }
}
42 true
  • Ptr<T> 是原生指针,FunPtr<F> 是 C 函数指针,sizeOf<T>() / alignOf<T>() 查询布局;
  • @CLayout struct 按 C 规则布局,可以按值传给 C 函数;
  • @Extern(lib = "…") 指定逻辑库名,captureErrno = true 让调用同时返回 errno;
  • @NoGC 标注保证函数不分配托管对象、不进入 GC;@Global / @ThreadLocal 声明原生全局存储;
  • Cone 可以携带 C/C++ 源码,与 Scoop 代码一起编译链接。

编码、解码与类型描述

要把一个 User 写成 JSON 再读回来,让它的公开 companion 实现 ValueEncoder<User> 和 ValueDecoder<User>,并用 @GenerateWith 选择 scoop.codec。构建时,生成器按字段生成两个方法。这里 note 的值为 None,写出时省略,读回时使用声明的默认值。

json.scoop
//! dep: scoop:scoop.json:0.1.0

import scoop.json.*

struct User(val name: String, val scores: Array<Int>, val note: String? = None) {
    @GenerateWith("scoop.codec", ["ValueEncoder<User>", "ValueDecoder<User>"])
    public companion object: ValueEncoder<User>, ValueDecoder<User>
}

fun main() {
    val original = User("Ada", [7, 9])
    val text = Json.encodeToString(original)
    println(text)
    val decoded = Json.decodeFromString<User>(text)
    println(f"${decoded.name}: ${decoded.scores[1L]}")
    println(decoded.note ?: "no note")
}
{"name":"Ada","scores":[7,9]} Ada: 9 no note

同一套编解码接口也用于 HTTP 请求和响应。解析命令行参数时,在实现 CliArguments<T> 的 companion 上选择 scoop.cli。见编解码规则和命令行示例。

要在程序中查询类型有哪些字段、变体或注解,可以用 typeInfo<T>() 取得静态类型描述。

package 与 import

Cone 中的每个文件以 package 声明开头,再用 import 引入其他包的名称:

package dev.example.app

import scoop.collections.*          // 整个包
import scoop.time.Duration          // 单个名称
import scoop.io.encoding.Base64

核心库的 prelude(println、Option 及其变体 Some/None、ArrayList、StringBuilder 等)默认可见。可见性修饰符有 public、internal(默认,Cone 内可见)、protected 和 private。

测试

测试放在 Cone 的 tests/ 目录中,依赖 scoop.test(在 [test-dependencies] 中声明)。用 @Test 标注测试类与测试方法,方法名可以用反引号写成一句话:

package examples.testing

import scoop.test.*

@Test
private class CalculatorTests {
    @Test
    fun `division returns a value`() {
        assertEquals(6, divide(42, 7))
        assertTrue(divide(42, 7) > 0)
    }

    @Test
    fun `zero count reports the reason`() {
        val error = assertFailsWith<IllegalArgumentException> { divide(42, 0) }
        assertEquals(Some("count must not be zero"), error.message)
    }
}

scoop test 运行选中的用例并逐项报告结果;断言库还提供前后置钩子、忽略标记等功能,见 scoop.test 的 API 文档。

继续深入

这份导览只覆盖了常用部分。属性委托、接口委托、inner class、匿名 object、task-local 上下文参数 context(name: T)、文档注释、原子类型与内存序、MaybeUninit<T> 等特性,请阅读参考文档;面向实现者的完整合同见 Scoop 语言规范。