Skip to content

Appendix D. Coming from Python, JavaScript or Java ​

This appendix does not reteach the language. It maps the habits you already have onto Sprig, one line at a time: on the left is what you are used to, on the right is what Sprig writes. Every Sprig fragment has run on the compiler; each section ends with a complete program that brings the most common differences together.

If you can already program, you can skim Chapters 1–4, but read Chapter 3 (numbers), Chapter 13 (values that may be missing) and Chapter 14 (errors) carefully — those are where Sprig differs from most languages.

D.1 Coming from Python ​

Python habitHow Sprig writes it
print(a, b)print takes one value: print(a); build the text first
1 / 2 gives 0.5Int / is rejected: 7.divTrunc(2) or 7.toFloatExact() / 2.toFloatExact()
// floor divisiona.divTrunc(b)
-7 % 3 gives 2-7 % 3 gives -1: the sign of % follows the dividend (as in Java)
if x: truthinessthe condition must be Bool: if x != 0:, if text != "":
len(s), len(xs)s.length() (String), xs.size() (collections)
f-string f"n = {n}""n = " + n; + turns the right side into text
Nonenull, which belongs only to T?; check != null before using it
try/excepterrors go into the signature: throws Error plus try/catch problem: Error:
lists are mutable by defaultList is read-only and MutableList is mutable; xs[0] = v becomes xs.set(0, v)
for i in range(n)the same: for i in range(n):
passthe same: pass
tuples (a, b)no tuples: a one-line class class Pair(first: Int, second: Int)
and, or, notthe same
d.get(k) returns Nonem.get(k) returns V?; m[k] is V? too, but m[k] += 1 requires the key to exist
spr
# Coming from Python: f-strings, None, mutable lists, // and %.
# Sprig joins text with + and marks missing values with T?.
let cups = 3
let price = 2.5
let total = cups.toFloatExact() * price
print("total: " + total)

func find(parts: List[String], name: String) -> String?:
    for part in parts:
        if part == name:
            return part
    return null

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

# Python lists are mutable by default; Sprig chooses MutableList explicitly.
let items: MutableList[String] = ["a", "b"]
items.append("c")
print(items)

# Python's // is divTrunc; % on negatives also differs from Python.
print(7.divTrunc(2))
print(-7 % 3)
print(7.toFloatExact() / 2.toFloatExact())
text
total: 7.5
found nut
[a, b, c]
3
-1
3.5

Line by line:

  • "total: " + total joins text and a Float, with no f-string and no str().
  • find returns String?; after if found != null:, found is a non-null string inside the branch.
  • items must be declared MutableList[String] before it can append; with List[String], append would be rejected.
  • 7.divTrunc(2) is deliberate truncation; -7 % 3 is -1 because the sign follows the dividend.
  • 7.toFloatExact() / 2.toFloatExact() is the fractional division, and gives 3.5.

D.2 Coming from JavaScript ​

JavaScript habitHow Sprig writes it
const / letlet binds once and var can be reassigned (the opposite of JS)
=== / !==== / !=, which are strict already: there are no implicit conversions
undefineddoes not exist; the only absence is null, and only inside T?
template strings `n = ${n}`"n = " + n
array.lengthxs.size()
array.push(v)xs.append(v)
array.map(f)xs.map(f); f is a typed lambda or a named function
{} object literals{"k": v} is a Map; for fixed fields use a one-line class
x?.y, x ?? yno optional chaining and no ??: write if x != null: first, or use or_else from @std/nulls
async/await, Promisesvirtual threads and tasks from @std/concurrent (Chapter 22)
function f(x) {}func f(x: Int) -> Int:, with a type on every parameter and the result
Math.floor(x)Float.floor(x); also sqrt, ceil and abs
parseInt(s)s.toIntOrNull() (returns null when missing) or s.toInt() (throws on failure)
NaN === NaN is falsetest with Float.isNaN(x); for approximate equality use x.approxEqual(y, tolerance)
for (const x of xs)for x in xs:
every number is a doubleInt is a 64-bit integer and Float is binary64; the two never mix implicitly
spr
# Coming from JavaScript: let/const, template strings, arrays and objects.
# Sprig's let binds once; var is the reassignable one.
var count = 0
let name = "Ada"
count += 1
print(name + " has " + count)

# JS's undefined does not exist; absence is T? plus null.
func lookup(ages: Map[String, Int], who: String) -> Int?:
    return ages.get(who)

let maybe = lookup({"ada": 36}, "bob")
if maybe == null:
    print("missing")
else:
    print(maybe)

# A JS array's length is a property; Sprig uses size() and [] for elements.
let numbers = [3, 1, 2]
print(numbers.size())
print(numbers[0])
print(numbers.contains(2))

# A JS object literal is a Map here; read fields with get.
let person = {"name": "Grace", "city": "London"}
print(person.get("name"))
print("city" in person)
text
Ada has 1
missing
3
3
true
Grace
true

Line by line:

  • var count can take count += 1; assigning to let name again would report SPR-NAME-LET-ASSIGN.
  • lookup returns Int? and {"ada": 36} is a Map[String, Int]; when nothing is found, get returns null.
  • numbers.size() is 3 and numbers[0] is 3; the array method is size(), not .length.
  • person.get("name") reads a value out of the map, and "city" in person tests keys.

D.3 Coming from Java ​

Java habitHow Sprig writes it
public static void main(String[] args)top-level statements are the program and run in source order; a function named main is not called automatically
System.out.println(x)print(x)
final local variableslet; for a local that can be reassigned, var
int overflow wraps aroundInt checks overflow, and overflow is a runtime error
integer / truncates/ is rejected: deliberate truncation is a.divTrunc(b)
int is 32-bit, long is 64-bitInt is 64-bit; write Int32 for 32 bits
double, floatFloat (binary64), Float32
a.equals(b)== already compares by value (numbers, Bool, String, lists, maps, enums, variants)
== on class objects compares referencesthe same: identity; equal fields do not make two objects equal
interfacescontract classes (methods without bodies) plus conform (Chapter 16)
extendsno inheritance; use contracts, composition or variants
generics <T>a generic T: block (Chapter 16)
checked exceptionsrecoverable errors are throws Error or an error class you define; checked Java exceptions are checked too
a Java method may return nullin Sprig that result is T?; you must check it before use
annotations, reflectionno annotations and no reflection-derived schemas; write explicit fields and functions
int[] arraysList[Int]; a Java array crosses as an opaque value (Appendix F)
spr
# Coming from Java: main, int overflow, interfaces, integer division.
# Sprig's top-level statements are the program; main is not called automatically.
class Account:
    let owner: String
    var balance: Int = 0

    func deposit(amount: Int) -> Unit:
        balance += amount

let account = Account(owner="Ada")
account.deposit(100)
print(account.owner + ": " + account.balance)

# No inheritance: a contract class (methods without bodies) plus conform replaces interfaces.
class Sink:
    func write(line: String) -> Unit

class Console:
    func write(line: String) -> Unit:
        print(line)

conform Console to Sink
let sink: Sink = Console()
sink.write("through the contract")

# Java's integer / truncates; Sprig rejects it and asks for intent.
print(7.divTrunc(2))
text
Ada: 100
through the contract
3

Line by line:

  • Account(owner="Ada") constructs the object with a named argument; deposit changes the var balance.
  • Sink's method has no body, so Sink is a contract class; after conform Console to Sink, a Console value can be used as a Sink.
  • 7.divTrunc(2) is 3: integer division must state its "truncate" intent.
  • Java's main is not called automatically, so the whole program above is top-level statements from beginning to end.

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