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:orif 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
# 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
letbinding can't be changed after it's set; avarcan. - 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 benullhas to be checked first (see Nullable values). - Conditions must be
Bool. Neither0nor an empty string counts as false, andif count:is rejected withSPR-TYPE-CONDITION.
Functions
# 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
throwsin its signature (see Errors).
Classes
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) orvar(can change), optionally with a default. - A small class with only
letfields and no methods fits on one line:class Position(x: Int, y: Int). It is the same kind of class as the block form;varfields, defaults and methods need the block. - A class whose methods have no body is a contract. Another class declares
conform Console to Sinkand must have every method of the contract with the same types; aConsolethen goes wherever aSinkis 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:
# 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
matchmust 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 Repositoryinside ageneric T:block isSPR-CLASS-ABSTRACT, and a generic class can'tconform. Write one contract per element type (IntRepository), or keep a generic class that holds the one operation as afnfield. - A contract is a type, never a bound.
requires T: SinkisSPR-GENERIC-CONSTRAINT: takeSinkas the parameter type,func drain(sink: Sink) -> Unit.requiresaccepts onlyEquatableandComparable. 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.
- A contract is never generic. A
- Also: a contract value never converts back to its class (no downcast), there's no type test on class or contract values and
matchis for enums and variants only;conformis 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 aSinkuntil it saysconform. - 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. TwoPoint(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
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
enumvalue carries no data, for exampleMode.Fast. - Each case of a
variantcan carry its own fields, which are immutable.Expr.Add, for example, carriesleftandright. case Expr.Add as node:binds the matched value tonodeso you can read its fields.- Variant and enum values compare by value:
Shape.Circle(radius=1.0) == Shape.Circle(radius=1.0)istrue. Strings, numbers, lists and maps do too. - A
matchmust handle every case. There's nodefault, no wildcard branch and no fallthrough. Missing, repeated and impossible branches are all compile errors. matchworks as a statement, where a branch can hold several lines, and as an expression (as inreturn 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
# 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"))ifproduces a value wherever an expressionmatchcan: after=,returnorthrow, and as a lambda's body. Each branch is one expression on its own indented line, andelifandelseline up with the line theifstarts on.- The
elsebranch 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 ordinaryifstatement: anifat the start of a statement is always theifstatement. - 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'tnull. Anullbranch makes the result nullable. - There's no
a if c else bas in Python and noc ? a : bas in C; the compiler points you to theifexpression instead. - Line breaks are ignored inside parentheses, so an
ifexpression can't go straight into a call, not even in a lambda's body there. Bind it, or the lambda that holds it, to aletfirst and pass the name, or pass a named function. The details are in if expressions.
Collections
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]andMap[K, V]are read-only; to change a collection, useMutableList[T]orMutableMap[K, V]. Modifying a read-only collection is rejected withSPR-COLLECTION-IMMUTABLE.toMutableList(),toList(),toMutableMap()andtoMap()copy the collection (the outer layer only), so the original stays as it was.- A list declared with
letand no type is aMutableList. It can be passed where aListis expected: the function sees the same list read-only, so a laterappendthrough the mutable name is visible to it, andtoList()takes a snapshot when you need one. AListnever becomes aMutableListwithouttoMutableList(). - Looking up a key in a
Mapgives you a nullable value:nullwhen the key isn't there. - Indexing,
in,get,set,append,sortand the lambda-taking methodsmap,filterandforEachall work. - Floating-point numbers can't be
Mapkeys, becauseNaNand 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):
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"))Coffee
Lunch
Taxi
food: 3050
transport: 3600
first ride: Taxi
true
2sort_byis a stable sort, and its key has to be orderable (seeComparablein generics).sortedsorts a list of orderable values such asList[String].group_byforms groups in the order their keys first appear and keeps the original order inside each group; keys are compared with==.sum_byadds up oneIntper element, andsumadds up aList[Int].findgives you the first element that passes the test, ornullwhen none does.any,allandcounttake the same kind of test.foldcombines 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,enumerateandzipcover the small list jobs;@std/setsaddsSet[T](sets.of[String]([...]),has,add,union);@std/random,@std/regexand@std/dateswrap one JDK facility each. The standard library notes list every function.
Nullable values
# 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?. OnlyT?acceptsnull. - Check before you use it. Inside
if x != null:,xhas a value. Since v0.6.0-beta.1,if x != null and x.length() > 3:works too. elifandelseknow the earlier conditions were false: afterif x == null:, anelif flag:branch and theelseboth treatxas present, with no second check. Writingx != nullagain there is accepted; it is just redundant.- Returning early works as well: after
if x == null: return ..., the rest of the code treatsxas present. Anif/elifchain 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
varlocal or a class field never narrows, whether or not a function is called in between: copy it into alet(let current = name) and check that. - Objects returned by Java methods are treated as possibly
null, except atoString()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:
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)12
0
{tea: 2, rice: 1}
8080
port must be a number: eightyor_elsereturns the value, or the fallback you give it when the value isnull.requirereturns the value, or throws anErrorwith your message when the value isnull.- 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
# 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
throwsin its signature. - The caller has two options: handle the error with
try/catch(optionally withfinally), or addthrowsto its own signature. Doing neither is rejected withSPR-FLOW-THROWS. - An
Errorhas amessagefield.print(problem),"failed: " + problemandproblem.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 itsmessageis aString?, because Java'sgetMessage()may returnnull. - Your own error types are error classes: a class with a
message: Stringfield plusconform NotFound to Error(message). Throw it, declare it withthrows NotFound, and catch it by name to read its fields, or asErrorto catch every kind at once. A catch of the class after a catch ofErroris unreachable and reported.
# 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
# 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
# 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
varlocal; that's rejected withSPR-TYPE-CAPTURE. Copy the value into aletfirst. - 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].printis a value only where afn(T) -> Unitis expected, such asitems.forEach(print). Java and built-in methods still take a lambda. Function values are not compared with==.
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
let inc: fn(Int) -> Int = fn(x: Int) => x + 1
print(inc(4))
let optional: (fn(Int) -> Int)? = nullfn(Int) -> Intis a type;fn(x: Int) => x + 1is 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 throwingErrorhas that type, and calling such a value needsthrows Errorortry/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
rethrowsinstead ofthrows: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/listshelpers work this way.
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)[1, 2]
caught: not a number: x
18
21
caught: not a number: threeA 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
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:
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)Read the tour {"id":1,"title":"Read the tour","done":true}
$[1].id: expected integer, found stringrequired_int,required_stringandrequired_boolreturn the field, or throw anErrorwhen it is missing,nullor 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 returnnullfor a missing ornullfield. rootreads a document that is an object, androot_arrayone that is a list.object,member,int,textandboolbuild the values to write back.
Modules
import "./math_module.spr" as math
print(math.square(7))
print(math.pi_approx)func square(x: Int) -> Int:
return x * x
let pi_approx: Float = 3.14159import "./file.spr" as aliasimports 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 inimport "@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 inread_utf8,max_byanduser_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.RedandT. - 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 (nameinsprig.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-STRINGon the unterminated literal. - Building a long text with
text += partin a loop takes time in proportion to the text when it happens in a function: the generated code keeps such a localvarin a builder instead of copying what is already there on every pass. A module-levelvaror a field doesn't get this, so build that text in a function, or collect the parts in a list andtext.jointhem. See building a String in a loop. sprig fmtformats 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 noexport *. See re-exports. - An expression
matchallows one expression per branch; for several lines, use a statementmatch. 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 " + countworks withouttoString(), and the value appears asprintwould show it.null, a value that may benull(such as anInt?) and aUnitresult are rejected. A chain evaluates from the left, so1 + 2 + " items"is3 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.
