Skip to content

Language quick reference ​

This page walks through Sprig's syntax from top to bottom. It's meant for people who already know another programming language and want to get going quickly. If Sprig is your first contact with the language, do the tutorial first and come back here to look things up.

Every piece of code on this page is a real file under website/snippets/ in the repository, and the docs check compiles and runs each one. To find out whether a feature is implemented, the feature status page has the final word.

Indentation and comments ​

Blocks are defined by indentation, as in Python:

  • Indent with spaces only; a tab is rejected with SPR-LEX-TAB. Keep the indentation within a block consistent; how many spaces you use is up to you.
  • The first line of code in a file starts in column 1.
  • A line indented where no block starts, or a header such as else: or if count > 0: with nothing indented under it, gets an error that names the problem.
  • Inside parentheses, brackets and braces you can break lines freely, so long calls and literals can span several lines.
  • # starts a comment.

Variables: let and var ​

spr
# let binds once; var may be reassigned.
let name = "Ada"
var visits = 0
visits += 1

# Local bindings infer their type from the initializer.
let greeting = "Hello, " + name
print(greeting)
print(visits)
  • A let binding can't be changed after it's set; a var can.
  • Local variables can leave out the type, and Sprig infers it from the right-hand side. Class fields always need a type.
  • To put a number or any other value into text, use +: "visits " + visits. There is nothing to convert first. A value that may be null has to be checked first (see Nullable values).
  • Conditions must be Bool. Neither 0 nor an empty string counts as false, and if count: is rejected with SPR-TYPE-CONDITION.

Functions ​

spr
# Named functions declare parameter and return types, including -> Unit.
func add(a: Int, b: Int) -> Int:
    return a + b

func factorial(n: Int) -> Int:
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(add(2, 3))
print(factorial(5))
  • Parameters and return values always have types. A function that returns nothing says -> Unit.
  • You call functions with positional arguments. Creating an object is different: you name the fields (see Classes below).
  • A function that can fail says throws in its signature (see Errors).

Classes ​

spr
class Hero:
    let name: String
    var health: Int = 100

    func heal(amount: Int) -> Unit:
        health += amount

    func describe() -> String:
        return name + " (" + health + " hp)"

# Class construction uses named fields only.
let hero = Hero(name="Ada", health=80)
hero.heal(15)
print(hero.describe())

# A record of let fields fits on one line; it is the same kind of class.
class Position(x: Int, y: Int)
let start = Position(x=0, y=3)
print(start)
print(start.y)
  • Fields are declared with let (fixed once the object exists) or var (can change), optionally with a default.
  • A small class with only let fields and no methods fits on one line: class Position(x: Int, y: Int). It is the same kind of class as the block form; var fields, defaults and methods need the block.
  • A class whose methods have no body is a contract. Another class declares conform Console to Sink and must have every method of the contract with the same types; a Console then goes wherever a Sink is expected and is used through the contract's methods. A contract has no fields, no default bodies, cannot be constructed, and there is no conversion back. Example:
spr
# A contract: a class whose methods have no body. Classes conform to it.
class Sink:
    func write(line: String) -> Unit
    func flush() -> Int

class Console:
    var written: Int = 0

    func write(line: String) -> Unit:
        written += 1
        print("console: " + line)

    func flush() -> Int:
        return written
conform Console to Sink

class Memory:
    let lines: MutableList[String] = []

    func write(line: String) -> Unit:
        lines.append(line)

    func flush() -> Int:
        return lines.size()
conform Memory to Sink

# The caller sees only the contract; any conforming object will do.
func log_all(lines: List[String], sink: Sink) -> Int:
    for line in lines:
        sink.write(line)
    return sink.flush()

print(log_all(["a", "b"], Console()))
print(log_all(["c"], Memory()))
  • When to use a variant and when a contract, in one line: a closed set of types is a variant; an open set is a contract. Closed means you list every case in one place and match must cover them all; open means any module can add another class that conforms.
  • Three rules about contracts are settled for the 0.8 language. They are decisions, not "not yet", and each rejection tells you what to write instead:
    • A contract is never generic. A class Repository inside a generic T: block is SPR-CLASS-ABSTRACT, and a generic class can't conform. Write one contract per element type (IntRepository), or keep a generic class that holds the one operation as a fn field.
    • A contract is a type, never a bound. requires T: Sink is SPR-GENERIC-CONSTRAINT: take Sink as the parameter type, func drain(sink: Sink) -> Unit. requires accepts only Equatable and Comparable. A contract doesn't conform to another contract either.
    • A contract has no default methods. Mixing methods with and without a body is SPR-CLASS-ABSTRACT. Write the shared behavior as a module function that takes the contract: func log_all(sink: Sink, lines: List[String]) -> Unit.
  • Also: a contract value never converts back to its class (no downcast), there's no type test on class or contract values and match is for enums and variants only; conform is written in the module that declares the class (you can't add it to an imported class), and a class with the right methods isn't a Sink until it says conform.
  • You create objects with field names: Hero(name="Ada", health=80). Missing, misspelled or repeated fields are compile errors.
  • Inside a method, a field's bare name refers to the current object's field; there's no prefix.
  • Parameters and local variables can't have the same name as a field.
  • == on two objects asks whether they're the same object. Two Point(x=1, y=2) objects are not ==, even though every field matches: change one and the other stays as it was. To compare contents, compare the fields you mean (a.id == b.id), or use a variant.

enum, variant and match ​

spr
variant Expr:
    Literal(value: Int)
    Add(left: Expr, right: Expr)

enum Mode:
    Fast
    Careful

# match must cover every case; there is no default branch.
func eval(expr: Expr) -> Int:
    match expr:
        case Expr.Literal as node:
            return node.value
        case Expr.Add as node:
            return eval(node.left) + eval(node.right)

func label(mode: Mode) -> String:
    match mode:
        case Mode.Fast:
            return "fast"
        case Mode.Careful:
            return "careful"

let tree = Expr.Add(
    left=Expr.Literal(value=20),
    right=Expr.Literal(value=22)
)
print(eval(tree))
print(label(Mode.Careful))
  • An enum value carries no data, for example Mode.Fast.
  • Each case of a variant can carry its own fields, which are immutable. Expr.Add, for example, carries left and right.
  • case Expr.Add as node: binds the matched value to node so you can read its fields.
  • Variant and enum values compare by value: Shape.Circle(radius=1.0) == Shape.Circle(radius=1.0) is true. Strings, numbers, lists and maps do too.
  • A match must handle every case. There's no default, no wildcard branch and no fallthrough. Missing, repeated and impossible branches are all compile errors.
  • match works as a statement, where a branch can hold several lines, and as an expression (as in return match ...), where each branch is a single expression.

Exhaustive matching pays off when code changes. Add a case to a variant, and every match that doesn't handle it fails to compile, so none slip through. tests/visitor/ast_visitor.spr in the repository, a small AST interpreter written in Sprig and run by the test suite, relies on exactly that.

Choosing a value with if ​

spr
# An if expression chooses a value. Each branch is one expression on its
# own line, and the else branch is required.
let count = 3
let label = if count == 1:
    "1 item"
else:
    count + " items"
print(label)

func shipping(cents: Int) -> Int:
    return if cents >= 5000:
        0
    elif cents >= 2000:
        299
    else:
        499

print(shipping(6400))
print(shipping(1200))

# Narrowing is the if statement's: after name == null, the elif and the
# else both use name directly.
func greet(name: String?) -> String:
    return if name == null:
        "Hello, stranger"
    elif name.length() > 8:
        "Hello, " + name.substring(0, 8) + "..."
    else:
        "Hello, " + name

print(greet(null))
print(greet("Ada"))
print(greet("Bartholomew"))
  • if produces a value wherever an expression match can: after =, return or throw, and as a lambda's body. Each branch is one expression on its own indented line, and elif and else line up with the line the if starts on.
  • The else branch is required; leave it out and you get "An if expression needs an else branch", while the rest of the file is still checked and the editor keeps working until you add it. When there's no value to produce, write an ordinary if statement: an if at the start of a statement is always the if statement.
  • All branches share one type: the type the position expects, as in let ratio: Float = if ..., or else the type of the first branch that isn't null. A null branch makes the result nullable.
  • There's no a if c else b as in Python and no c ? a : b as in C; the compiler points you to the if expression instead.
  • Line breaks are ignored inside parentheses, so an if expression can't go straight into a call, not even in a lambda's body there. Bind it, or the lambda that holds it, to a let first and pass the name, or pass a named function. The details are in if expressions.

Collections ​

spr
let immutable: List[Int] = [3, 1, 2]
let mutable: MutableList[Int] = immutable.toMutableList()
mutable.append(4)
mutable.sort()

print(immutable.contains(2))
print(2 in immutable)
print(mutable)
print(mutable[0])
print(immutable)  # toMutableList returns a new outer collection

let ages: Map[String, Int] = {"ada": 36, "bob": 41}
print(ages.get("ada"))
print(ages["missing"])
print("bob" in ages)
  • List[T] and Map[K, V] are read-only; to change a collection, use MutableList[T] or MutableMap[K, V]. Modifying a read-only collection is rejected with SPR-COLLECTION-IMMUTABLE.
  • toMutableList(), toList(), toMutableMap() and toMap() copy the collection (the outer layer only), so the original stays as it was.
  • A list declared with let and no type is a MutableList. It can be passed where a List is expected: the function sees the same list read-only, so a later append through the mutable name is visible to it, and toList() takes a snapshot when you need one. A List never becomes a MutableList without toMutableList().
  • Looking up a key in a Map gives you a nullable value: null when the key isn't there.
  • Indexing, in, get, set, append, sort and the lambda-taking methods map, filter and forEach all work.
  • Floating-point numbers can't be Map keys, because NaN and signed zero don't behave consistently under equality and hashing.

To sort by a field, group, total things up or search, use @std/lists from the standard library (new in v0.6.0-beta.1):

spr
import "@std/lists.spr" as lists

class Expense:
    let item: String
    let category: String
    let cents: Int

let expenses: List[Expense] = [
    Expense(item="Coffee", category="food", cents=1250),
    Expense(item="Taxi", category="transport", cents=3600),
    Expense(item="Lunch", category="food", cents=1800),
]

for expense in lists.sort_by(expenses, fn(e: Expense) => e.cents):
    print(expense.item)

for group in lists.group_by(expenses, fn(e: Expense) => e.category):
    let total = lists.sum_by(group.items, fn(e: Expense) => e.cents)
    print(group.key + ": " + total)

let ride = lists.find(expenses, fn(e: Expense) => e.category == "transport")
if ride != null:
    print("first ride: " + ride.item)
print(lists.any(expenses, fn(e: Expense) => e.cents > 3000))
print(lists.count(expenses, fn(e: Expense) => e.category == "food"))
text
Coffee
Lunch
Taxi
food: 3050
transport: 3600
first ride: Taxi
true
2
  • sort_by is a stable sort, and its key has to be orderable (see Comparable in generics). sorted sorts a list of orderable values such as List[String].
  • group_by forms groups in the order their keys first appear and keeps the original order inside each group; keys are compared with ==.
  • sum_by adds up one Int per element, and sum adds up a List[Int].
  • find gives you the first element that passes the test, or null when none does. any, all and count take the same kind of test.
  • fold combines the elements from left to right into one result, for anything the functions above don't cover.
  • first, last, take, drop, reversed, distinct, index_of, enumerate and zip cover the small list jobs; @std/sets adds Set[T] (sets.of[String]([...]), has, add, union); @std/random, @std/regex and @std/dates wrap one JDK facility each. The standard library notes list every function.

Nullable values ​

spr
# T? marks expected absence. A checked value narrows to non-null inside the branch.
func find(words: List[String], target: String) -> String?:
    for word in words:
        if word == target:
            return word
    return null

let found = find(["alpha", "beta"], "beta")
if found != null:
    print("found " + found)
else:
    print("not found")

let missing = find(["alpha"], "gamma")
print(missing == null)

# elif and else see the earlier conditions false: no second check is needed.
func describe(count: Int?, verbose: Bool) -> String:
    if count == null:
        return "none"
    elif verbose:
        return "count " + count
    else:
        return "quiet " + count

print(describe(3, true))
print(describe(null, true))
  • A type that might have no value is written T?. Only T? accepts null.
  • Check before you use it. Inside if x != null:, x has a value. Since v0.6.0-beta.1, if x != null and x.length() > 3: works too.
  • elif and else know the earlier conditions were false: after if x == null:, an elif flag: branch and the else both treat x as present, with no second check. Writing x != null again there is accepted; it is just redundant.
  • Returning early works as well: after if x == null: return ..., the rest of the code treats x as present. An if/elif chain whose earlier branches all return works the same way.
  • Using a possibly-null value where a value is required is rejected with SPR-TYPE-NULLABLE.
  • A var local or a class field never narrows, whether or not a function is called in between: copy it into a let (let current = name) and check that.
  • Objects returned by Java methods are treated as possibly null, except a toString() result and results the library annotates as non-null; see JVM interop.

When all you want is a fallback value or an error, @std/nulls (new in v0.6.0-beta.1) saves the if:

spr
import "@std/nulls.spr" as nulls

# A fallback for a missing value, in one line.
let stock: Map[String, Int] = {"tea": 12}
print(nulls.or_else(stock["tea"], 0))
print(nulls.or_else(stock["milk"], 0))

# Counting: start from 0 when the key is not there yet.
let counts: MutableMap[String, Int] = {}
for word in ["tea", "rice", "tea"]:
    counts[word] = nulls.or_else(counts[word], 0) + 1
print(counts)

# No sensible fallback: stop with an error that says what was missing.
func port(text: String) -> Int throws Error:
    return nulls.require(text.toIntOrNull(), "port must be a number: " + text)

try:
    print(port("8080"))
    print(port("eighty"))
catch problem: Error:
    print(problem.message)
text
12
0
{tea: 2, rice: 1}
8080
port must be a number: eighty
  • or_else returns the value, or the fallback you give it when the value is null.
  • require returns the value, or throws an Error with your message when the value is null.
  • Neither needs a type in brackets: like any generic call, it takes the type from the value you pass. (That's newer than v0.7.1-beta.1, where you write nulls.or_else[Int](...).)

Errors ​

spr
# Recoverable failures use typed errors: func ... throws T, throw, try/catch.
func checkout(quantity: Int) -> Int throws Error:
    if quantity <= 0:
        throw Error("quantity must be positive")
    return quantity * 3

try:
    print(checkout(4))
catch problem: Error:
    print("rejected: " + problem.message)

try:
    print(checkout(0))
catch problem: Error:
    print("rejected: " + problem.message)
  • A function lists the errors it can throw with throws in its signature.
  • The caller has two options: handle the error with try / catch (optionally with finally), or add throws to its own signature. Doing neither is rejected with SPR-FLOW-THROWS.
  • An Error has a message field. print(problem), "failed: " + problem and problem.toString() show that same message.
  • Java checked exceptions are caught the same way: name the imported Java exception class after catch. Such an exception shows Java's text, class name first, and its message is a String?, because Java's getMessage() may return null.
  • Your own error types are error classes: a class with a message: String field plus conform NotFound to Error(message). Throw it, declare it with throws NotFound, and catch it by name to read its fields, or as Error to catch every kind at once. A catch of the class after a catch of Error is unreachable and reported.
spr
# An error class: a class with a message field that conforms to Error.
class NotFound:
    let message: String
    let sku: String
conform NotFound to Error(message)

func stock(sku: String) -> Int throws NotFound:
    if sku == "A1":
        return 7
    throw NotFound(message="no item " + sku, sku=sku)

func describe(sku: String) -> String:
    try:
        return "stock " + stock(sku)
    catch problem: NotFound:
        return "missing sku " + problem.sku

print(describe("A1"))
print(describe("ZZ"))
try:
    print(stock("QQ"))
catch problem: Error:
    print("as Error: " + problem.message)

Generics ​

spr
# Generics: one or more parameters per block. A call or constructor takes its
# type arguments from its arguments; Box[Int](value=41) would mean the same.
generic T:
    class Box:
        let value: T

generic T:
    func identity(value: T) -> T:
        return value

let box = Box(value=41)
print(identity(box.value) + 1)

Your own classes, variants and functions can go inside a generic T: (or generic K, V:) block. A call works out the type arguments from its arguments, so Box(value=42) is a Box[Int] (newer than v0.7.1-beta.1, which needs Box[Int](value=42)). When the arguments can't say, as with an empty list, you write them yourself: lists.first[String]([]). Generics have no variance. To compare values of a type parameter with ==, start the function with requires T: Equatable; to order them with <, use requires T: Comparable. The generics guide has the details.

Lambdas ​

spr
# Lambdas are expressions: fn(params) => expression. Arities 0 through 3.
let doubled = [1, 2, 3].map(fn(x: Int) => x * 2)
print(doubled)

let evens = [1, 2, 3, 4].filter(fn(x: Int) => x % 2 == 0)
print(evens)

let collected: MutableList[Int] = []
[1, 2, 3].forEach(fn(x: Int) => collected.append(x * 10))
print(collected)
  • A lambda is an expression: fn(x: Int) => x * 2.
  • It takes 0 to 3 parameters and its body is a single expression. It may call a function that throws Error; its type then says so (see Function types below).
  • A lambda can't capture a var local; that's rejected with SPR-TYPE-CAPTURE. Copy the value into a let first.
  • A named function, module function or method without the call parentheses is a function value: items.map(shout), lists.sum, counter.bump. Its type is the forwarding lambda's, throws clause included. A method reference evaluates its receiver once, when the value is created. A generic function writes its type arguments: identity[Int]. print is a value only where a fn(T) -> Unit is expected, such as items.forEach(print). Java and built-in methods still take a lambda. Function values are not compared with ==.
spr
import "@std/lists.spr" as lists

func shout(text: String) -> String:
    return text.toUpperCase() + "!"

class Counter:
    var count: Int = 0

    func bump(by: Int) -> Int:
        count += by
        return count

let words = ["pear", "fig"]
print(words.map(shout))               # a named function as a value
let total: fn(List[Int]) -> Int = lists.sum
print(total([1, 2, 3]))               # a module function as a value
let counter = Counter()
let bump = counter.bump               # a method reference: the receiver is fixed now
print(bump(2))
print(bump(3))
print(counter.count)
words.forEach(print)                  # print where a fn(String) -> Unit is expected
let flip = lists.reversed[String]     # a generic function writes its type arguments
print(flip(words))

Function types ​

spr
let inc: fn(Int) -> Int = fn(x: Int) => x + 1
print(inc(4))
let optional: (fn(Int) -> Int)? = null
  • fn(Int) -> Int is a type; fn(x: Int) => x + 1 is a value.
  • Function types take 0 to 3 parameters. Parameter and result types must match exactly: there's no function subtyping and no automatic conversion.
  • To make the whole function nullable, add parentheses: (fn(Int) -> Int)?. fn(Int) -> Int? means the result is nullable. Check a nullable function value before calling it, like any nullable value.
  • Function types can be used for variables, fields, parameters and results, and as explicit generic arguments.
  • A function type may end with throws Error, and nothing else: fn(String) -> Int throws Error. A lambda that calls a function throwing Error has that type, and calling such a value needs throws Error or try/catch, like any throwing call. A value without the clause is accepted where the clause is expected, never the other way round (SPR-TYPE-CALLABLE-THROWS). A checked Java exception never crosses a function value; handle it inside a named function.
  • A function that only passes its callable's errors on is declared rethrows instead of throws: func twice(step: fn(Int) -> Int throws Error, value: Int) -> Int rethrows:. A call to it throws exactly what the lambda you pass throws, so a lambda that cannot fail makes an ordinary call. The @std/lists helpers work this way.
spr
import "@std/lists.spr" as lists

func to_number(text: String) -> Int throws Error:
    let value = text.toIntOrNull()
    if value != null:
        return value
    throw Error("not a number: " + text)

# The lambda calls a throwing function, so its type is
# fn(String) -> Int throws Error, and the call through map throws too.
func numbers(items: List[String]) -> List[Int] throws Error:
    return items.map(fn(item: String) => to_number(item))

# rethrows: twice throws exactly what step throws. With a lambda that cannot
# fail, the call needs no try and no throws.
generic T:
    func twice(step: fn(T) -> T throws Error, value: T) -> T rethrows:
        return step(step(value))

try:
    print(numbers(["1", "2"]))
    print(numbers(["1", "x"]))
catch problem: Error:
    print("caught: " + problem)
print(twice(fn(n: Int) => n * 3, 2))
let parse: fn(String) -> Int throws Error = fn(text: String) => to_number(text)
try:
    print(parse("21"))
    print(lists.sum_by(["1", "2", "three"], fn(text: String) => parse(text)))
catch problem: Error:
    print("caught: " + problem)
text
[1, 2]
caught: not a number: x
18
21
caught: not a number: three

A function value can go where Java expects a functional interface with up to three parameters, such as Comparator, Consumer or Runnable, and where it expects one of Sprig's own sprig.runtime.Fn0 to Fn3 types; see JVM interop. If you're not sure, sprig api <Class> --json shows the actual signature.

Looking up JSON fields ​

spr
import "@std/json.spr" as json

let document = json.parse("{\"name\":null}")
match json.find_member(document, "name"):
    case json.Lookup.Missing:
        print("missing")
    case json.Lookup.Found as member:
        print(json.stringify(member.value))  # prints null
    case json.Lookup.NotObject:
        print("expected an object")

json.find_member has three outcomes: Missing (no such key), Found (the value is in value) and NotObject (you didn't look inside an object). A key whose value is null, false, 0 or an empty string is still Found, so it never gets confused with a missing key. Duplicate keys in an object throw an Error, and members keep their order. The standard library notes cover parsing, lookup and serialization in full.

To read whole records, @std/json_codec (new in v0.6.0-beta.1) takes a field by name and type, so you don't write a match for every field:

spr
import "@std/json.spr" as json
import "@std/json_codec.spr" as codec

class Task:
    let id: Int
    let title: String
    let done: Bool

func decode_task(row: codec.Reader) -> Task throws Error:
    return Task(
        id=codec.required_int(row, "id"),
        title=codec.required_string(row, "title"),
        done=codec.required_bool(row, "done")
    )

func encode_task(task: Task) -> json.Value:
    return codec.object([
        codec.member("id", codec.int(task.id)),
        codec.member("title", codec.text(task.title)),
        codec.member("done", codec.bool(task.done))
    ])

let text = "[{\"id\": 1, \"title\": \"Read the tour\", \"done\": true}, {\"id\": \"2\", \"title\": \"Write code\", \"done\": false}]"
for row in codec.root_array(json.parse(text)):
    try:
        let task = decode_task(row)
        print(task.title + " " + json.stringify(encode_task(task)))
    catch problem: Error:
        print(problem.message)
text
Read the tour {"id":1,"title":"Read the tour","done":true}
$[1].id: expected integer, found string
  • required_int, required_string and required_bool return the field, or throw an Error when it is missing, null or another kind. Nothing is converted: the string "2" is not an integer.
  • Every message starts with where the problem is, here element 1 of the list, field id.
  • The optional_ versions return null for a missing or null field.
  • root reads a document that is an object, and root_array one that is a list.
  • object, member, int, text and bool build the values to write back.

Modules ​

spr
import "./math_module.spr" as math

print(math.square(7))
print(math.pi_approx)
spr
func square(x: Int) -> Int:
    return x * x

let pi_approx: Float = 3.14159
  • import "./file.spr" as alias imports another Sprig file.
  • Imports go at the top of the file, before any declaration or statement.
  • Each module is initialized once. Two modules importing each other (an import cycle) is rejected with SPR-NAME-IMPORT-CYCLE.
  • Java classes are imported the same way, with the full class name: import java.time.LocalDate as LocalDate.
  • The standard library starts with @std, as in import "@std/json.spr" as json.

Names ​

Names follow what Sprig code already writes:

  • A name you declare is lowercase with underscores: functions, methods, parameters, variables, fields, module-level lets and import aliases, as in read_utf8, max_by and user_id. An acronym is lowercase too: write_utf8, escape_html.
  • Types are UpperCamelCase: classes, contracts, variants and enums, their cases and type parameters, as in HttpServer, Expr.Literal, Color.Red and T.
  • There are no all-caps constants.
  • The built-in members of the native types (toString, toFloatExact, divTrunc, toIntOrNull) and Java APIs (ArrayList.add, Thread.MIN_PRIORITY) keep their camelCase names. A method that implements or overrides a Java method uses the Java name.
  • Files and directories are lowercase with underscores too: json_codec.spr, main.spr. Package names (name in sprig.toml, registry names) are lowercase with hyphens: sprig-web.

The all-caps cases of sprig-cli's OptionKind.FLAG and sprig-web's Method.GET and SchemaType.STRING came earlier and stay.

A few smaller features ​

  • String literals must close on the same line. A missing closing quote or a newline inside a string reports SPR-LEX-STRING on the unterminated literal.
  • Building a long text with text += part in a loop takes time in proportion to the text when it happens in a function: the generated code keeps such a local var in a builder instead of copying what is already there on every pass. A module-level var or a field doesn't get this, so build that text in a function, or collect the parts in a list and text.join them. See building a String in a loop.
  • sprig fmt formats code in one standard style. It keeps your comments and has no options. See formatter.
  • A module can re-export an imported declaration with export alias.Symbol, but that can't be used to get around a dependency's exports. There's no export *. See re-exports.
  • An expression match allows one expression per branch; for several lines, use a statement match. See match expressions.

Not in the language yet ​

None of these exist yet:

  • inferring type arguments from the expected type, and variance
  • inheritance (open polymorphism is a contract class, see Classes)
  • %=
  • tuples and destructuring
  • string interpolation: "${name}" is just text. Join with + instead: it accepts any value on either side, so "count " + count works without toString(), and the value appears as print would show it. null, a value that may be null (such as an Int?) and a Unit result are rejected. A chain evaluates from the left, so 1 + 2 + " items" is 3 items.

When working with Java, Sprig has no array syntax and no wildcard syntax of its own. Java arrays can still be received and passed along as they are, varargs methods take their trailing arguments, and Java wildcards keep their bounds; see JVM interop.

The full list is in known limitations, and what comes next is in the roadmap.

Sprig is licensed under Apache-2.0 · v0.7.1-beta.1 published as a prerelease