Types
Built-in types, numbers, strings, unit, tuples, functions, and the top and bottom types.
Built-in types
Built-in type names are lowercase and belong to the language itself: they have no module path and
cannot be shadowed by an import. In a pattern each is a
type pattern by itself, x is int, so none names a
local, a parameter or a field. Their methods are defined in the core standard library with
ordinary impl blocks.
| Type | Meaning |
|---|---|
int | Alias of i32 |
long | Alias of i64; int and long are the only integer aliases |
iN | Signed integer of exactly N bits, 1 ≤ N ≤ LLVM’s limit (i8, i64, i128, i257, …) |
byte | An octet, 0–255: the unit of binary data |
real | IEEE-754 binary64. There is no single-precision type |
char | A Unicode scalar value (U+0000–U+10FFFF, excluding surrogates) |
bool | true or false |
string | Immutable UTF-8 text |
unit | One value, written () |
All other types — user types, library types, collections — are PascalCase by convention.
Integers
Arithmetic keeps the operand width: i8 + i8 is i8. Mixed widths need an explicit conversion
(long(x)); there is no implicit widening. Diagnostics name i32 and i64 by their aliases, and
an operation or comparison on two number types names the conversion that joins them, pointing at
the operand to convert: error: `*` needs two numbers of one type, not long and int; write `long(n)` (an integer converts to the wider integer or to real, a byte to the other side’s
type; a compound assignment’s target keeps its type, so there the value converts to it). A literal takes its width from context (an annotation,
a parameter, the other operand, the other branches of an if or elements of a collection literal) and defaults to int; a literal that does not fit is a compile error.
Where a real is expected, an integer literal is that real (x * 2), provided it is exact: its
magnitude is at most 2^53.
Conversions: widening sign-extends; narrowing traps when the value does not fit the narrower width
(i8(300) traps, i8(127) is 127), and i8.wrap(300) is the explicit wrapping form, which keeps the low
bits (44); real-to-integer
truncates toward zero, saturates at the bounds and maps NaN to zero; char(n) traps on a value that
is not a Unicode scalar. Conversions are written as a call of the target type, and these exist: between
any two integer types; integers and real in both directions; an integer or byte to byte and
char; byte and char to any integer type; byte to real. A conversion to the same type is
allowed and does nothing.
Limits. Every integer type has its least and greatest value as constants, MinValue and MaxValue:
int.MaxValue, long.MinValue, i8.MaxValue, i1.MinValue, i257.MaxValue, and byte.MaxValue (255)
and byte.MinValue (0). char.MaxValue is U+10FFFF and char.MinValue U+0000. real has MaxValue
(the greatest finite value), MinValue (the least, its negation), MinPositiveValue (the least positive
value, subnormal), PositiveInfinity, NegativeInfinity and NaN. They are written on the type, are
folded at compile time, and have the type they are written on; a type parameter bounded by Integer
has MinValue and MaxValue too, folded at each instance’s width (generics). Any other name written on one of these
types is an error.
Arithmetic that overflows traps. +, -, *, unary -, ++ and -- trap when the
mathematical result does not fit the width, and so does / for the one quotient that cannot fit
(MIN / -1). % never overflows: MIN % -1 is 0. Division and remainder by zero trap. Code that
wants other behaviour says so with an operator: +%, -% and *% wrap, and +|, -| and *|
saturate at the bounds. Shifts never trap; a count at least as large as the width, or a negative
count, shifts every bit out (>> keeps the sign, so -1 >> 40 is -1).
Integers are signed; there are no unsigned integer types. Binary data uses byte.
The integer types are one family, iN for every width from i1 to i8388608, and the closed core
trait Integer has exactly them as members (byte is not one). The core library implements its
traits once for the whole family, so every width compares, orders, prints in decimal and debugs
alike, and meets a bound such as Ord or Display as int does; a parameter bounded by Integer
has every integer operation and conversion (Bounds). The integers and real
together are the numbers, the members of the core trait Numeric, which Integer requires: a
parameter bounded by it has the arithmetic, the ordering and toReal. A value that fits in a
long renders through it, at no cost for widths up to 64 bits; a wider one renders in chunks of
eighteen digits.
Integer methods. Every integer type has these methods, from one impl for the whole family, each
working at the width it is called at (an i8 stays an i8) and trapping, as arithmetic does, when
a result does not fit:
| Method | Result |
|---|---|
abs | The magnitude; traps for MinValue, whose magnitude does not fit |
sign | -1, 0 or 1, as an int at every width |
pow(n) | The number to the power n, an int; x.pow(0) is 1, 0.pow(0) included. Traps when the result does not fit and when n is negative |
gcd(o) | The greatest common divisor, never negative; 0.gcd(0) is 0. Traps only when it is MinValue‘s magnitude, as in MinValue.gcd(0) |
lcm(o) | The least positive common multiple, 0 when either is 0; traps when it does not fit |
floorDiv(o), floorMod(o) | The quotient rounded towards negative infinity, and the remainder that takes the divisor’s sign, so a == a.floorDiv(d) * d + a.floorMod(d). They trap where / and % do: a zero divisor, and MinValue.floorDiv(-1) |
bitCount | The number of one bits of the two’s-complement form at the width: (-1).bitCount is 32 for an int |
leadingZeros, trailingZeros | The zero bits above the highest one and below the lowest one, an int; the width for zero. leadingZeros is 0 for a negative number |
isPowerOfTwo | Whether the number is 1, 2, 4, and so on; never for zero or a negative number |
toRadix(r) | The digits in radix r from 2 to 36, lower case, with a - for a negative number and no prefix, as f"%x" and f"%b" write them; any other radix traps |
toInt, toLong | The number as an int or a long, exactly int(n) and long(n): trapping when it does not fit |
toReal | The number as a real, exactly real(n); it is Numeric‘s, so generic code has it too |
The bitwise operators &, |, ^ and the shifts also work on a type parameter bounded by
Integer, as the machine’s operators at each width, with both operands of one type: x >> T(1).
The methods above are not members of Integer, so generic code cannot call them on a T.
BigInt
BigInt, a class of the core library, is a whole number of any size: it holds as many digits as
its value needs, so its arithmetic never overflows. It is not a member of Integer, whose widths are
fixed, but it is a number, an ordered value and a key: it implements Numeric (the five operators,
unary -, Ord, Display, Debug, BigInt.zero(), BigInt.one() and toReal), Eq and Hash
by value.
var f: BigInt = 1
for i in 2 .. 100 do f *= i
println(f) // 100!, all 158 digits
println(f % 1000 == 0) // true
println(f"${BigInt(2).pow(100)}%,d") // 1,267,650,600,228,229,401,496,703,205,376
val big: BigInt = 123456789012345678901234567890
println(big * 2 + 1) // 246913578024691357802469135781
println(BigInt("ff", 16) + 1) // 256
println(BigInt.parse("12x")) // None
- Making one. A
BigInttakes integers byFromInteger: where one is expected, an integer literal of any size and base is thatBigInt(val big: BigInt = 123456789012345678901234567890,val m: BigInt = 0xffffffffffffffffffffffff), and an integer of any width beside one under an operator is converted to one.BigInt(n)takes an integer of any width; a literal argument there is along, so it may be as large as one.BigInt(text)reads decimal andBigInt(text, radix)digits of base 2 to 36 (0to9, thenatozin either case), each after an optional-or+, with at least one digit and nothing else: no white space, separators, prefix or exponent. Text that is not that traps, astoLongdoes;BigInt.parse(text)andBigInt.parse(text, radix)answerNoneinstead. A radix outside 2 to 36 traps under both, being the caller’s mistake.-0is zero, and zero has no sign. - Arithmetic is exact.
+,-,*and unary-never trap, between twoBigInts or aBigIntand an integer on either side:f * i,i * f,f - 1,f /= n. The comparisons and==take an integer on either side too, chains included:f == 0,0 < f < limit. The bitwise, shift, wrapping and saturating operators are the integers’ alone./rounds towards zero and%takes the dividend’s sign, as on the integer types;floorDivandfloorModround towards negative infinity, anddivRem(o)gives(self / o, self % o)from one division. A zero divisor traps withdivision by zerounder every one of them. - Methods.
isZero;sign,abs,pow(n),gcd(o),lcm(o)andtoRadix(r)as the integer types have them, except that nothing overflows:powtraps only for a negativen, andgcdandlcmnever.toLongandtoIntgive the value as that type and trap when it does not fit, withvalue out of range for long(orint);toLongOptionandtoIntOptionanswerNoneinstead.toRealis the nearestreal, a tie going to the even one, and an infinity of the number’s sign past the greatest finitereal. - Text. A
BigIntdisplays as an integer does, in decimal with a-when negative, and itsDebugform is the same. The integer conversions%d,%i,%x,%X,%oand%btake it with every flag, width and precision, laying it out exactly as they lay out alongof the same value; like every number it is refused under%s,%fand%c. - Representation. The magnitude is held in limbs of nine decimal digits, least significant first,
never written once made, so a
BigIntis an immutable value that may be shared freely. Decimal text is read and written a limb at a time; other bases go through division by a power of the radix. Multiplication and division are the schoolbook algorithms, quadratic in the number of limbs. - Identities.
BigInt.zero()andBigInt.one()areAdd‘s andMul‘s static members, kept with()as every type’s are;val z: BigInt = 0is the same value.
Integers meet a type that takes them
A type that implements the core trait FromInteger takes integers, of every width and without loss.
BigInt is the library’s one; a program’s own number type joins by implementing it:
trait FromInteger
static fromInteger[N: Integer](n: N) -> Self
- A literal where one is expected is its value, wherever a type is expected: an annotation, an
argument, a default, a result, a branch of an
if, a collection literal’s element, and the other operand of an operator. The literal may be of any size and in any base, with separators; it is passed tofromIntegeras alongwhere it fits one, and otherwise as the narrowest wider integer that holds it (i128,i192, …). A type parameter bounded byFromIntegertakes one the same way:val x: T = 42isT.fromInteger(42)in each instance. - An integer operand beside one is converted to it. In
a op b, whereopis+,-,*,/or%, and in a comparison or==/!=, an operand whose type is an integer, or a type parameter bounded byInteger, meets an operand of a type that takes integers asT.fromInteger(n), on either side:big * i,i * big,big < n,0 == big. A chain converts each integer beside such an operand. The converted operand is evaluated once, where it stands. A compound assignment converts its value into aBigInttarget,f *= i; an integer target keeps its type, son += bigis an error. Where the type has an operator method of the operator’s name and no overload of it takes an integer, its integer argument is converted too, and an integer on its left calls it. - Nothing else converts. Two integer widths still meet only through a conversion (
long(x)), arealor abytenever converts to a type that takes integers, nor such a value back to an integer,===compares no converted value, and the bitwise, shift, wrapping and saturating operators stay the integers’ own. An integer literal is no pattern for such a type, since its value is a call and not a constant:b match 0 -> …is an error that says to compare with==.
BigDecimal
BigDecimal, a class of the core library beside BigInt, is a decimal number of any size and any
number of places: an unscaled BigInt and a scale, the count of its digits after the point, so
19.99 is 1999 at scale 2. Where a real holds the nearest binary fraction, a BigDecimal holds
the decimal exactly, which makes it the number for money and for anything else written in decimal.
It is immutable, and a number, an ordered value and a key: it implements Numeric, Eq and Hash
by value, FromInteger and FromDecimal.
main()
val price: BigDecimal = 19.99
println(price * 3) // 59.97
val tenth: BigDecimal = 0.1
println(tenth + 0.2 == 0.3) // true
val one: BigDecimal = 1
println(one / 3) // 0.3333333333333333333333333333333333
println(one.div(3, scale = 4)) // 0.3333
println(one.exactDiv(8)) // Some(0.125)
println(one.exactDiv(3)) // None
val x: BigDecimal = 2.345
println(x.round(2)) // 2.34
println(x.round(2, rounding = HalfUp)) // 2.35
val two: BigDecimal = 2.0
println(two == 2.00) // true
println(BigDecimal.fromRealShortest(0.1)) // 0.1
println(f"$x%.1f") // 2.3
59.97
true
0.3333333333333333333333333333333333
0.3333
Some(0.125)
None
2.34
2.35
true
0.1
2.3
- Making one. A decimal literal where a
BigDecimalis expected is that number, read from its digits, never through areal:val price: BigDecimal = 19.99holds exactly 19.99, and1.5e-3,1_000.25and-0.5are read the same way. An integer literal of any size is one at scale 0, and an integer or aBigIntbeside one under an operator is converted to one.BigDecimal(n)takes an integer of any width or aBigInt, andBigDecimal(unscaled, scale)names both parts; a negative scale traps.BigDecimal(text)reads an optional-or+, digits with an optional point among or around them, and an optional exponent (eorE, an optional sign, digits); the scale is the digits after the point less the exponent, and 0 where that is below 0, so"1.50"is scale 2 and"1.5e3"is1500. Nothing else is read, no white space or separators; other text traps, andBigDecimal.parse(text)answersNoneinstead, as it does for a scale beyond anint. - From a
real, only explicitly. Arealnever converts on its own:d + ris an error that names the two conversions.BigDecimal.fromRealExact(x)is the binary fractionxholds, every digit of it (0.1gives0.1000000000000000055511151231257827021181583404541015625), andBigDecimal.fromRealShortest(x)the shortest decimal that reads back asx, asxprints (0.1). Both take the least scale that holds the value, and NaN and the infinities trap.toRealis the nearestreal, a tie going to the even one, and an infinity of the number’s sign beyond the greatest finite one. - Rounding.
Roundingis a data type of seven variants:HalfEven, the nearer neighbour with a tie to the even digit, the default wherever a rounding is taken;HalfUpandHalfDown, a tie away from and toward zero;UpandDown, away from and toward zero;CeilingandFloor, toward positive and negative infinity. There is no mode that traps on an inexact result: an operation that must be exact answers anOptioninstead.x.round(places)gives the number at that scale, its other digits rounded, and a shorter one gains zeros (2.5at two places is2.50); a negativeplacesrounds to tens, hundreds and so on, written as a whole number.x.roundSignificant(n)rounds to at mostnsignificant digits. Each takesrounding = …by name. - Arithmetic.
+,-,*and unary-are exact: a sum has the larger scale and a product the sum of the scales./gives the quotient to 34 significant digits, rounded half to even; where the exact quotient has no more digits than that, it is exact, with no zeros after it beyond the dividend’s scale less the divisor’s (1 / 4is0.25,6.00 / 2is3.00).a.div(b, scale = n, rounding = r)gives the quotient atnplaces anda.divSignificant(b, n, rounding = r)tonsignificant digits,/beingdivSignificant(b, 34).a.exactDiv(b)answers the exact quotient, orNonewhere it never ends; where/is exact the two agree.%is what is left once the quotient cut to a whole number is taken away, with the dividend’s sign, anddivRem(b)answers that whole quotient and the remainder from one division.pow(n)is exact. A zero divisor traps withdivision by zerounder every one of them. - Equality is by value.
==, the ordering and the hash look at the number, not its scale:2.0 == 2.00, the two hash alike, and they are one key of a map and one member of a set.scaletells them apart, andstripTrailingZerosgives the number at the least scale that holds it (2.500is2.5; a whole number keeps its zeros before the point). - Mixing. An integer of any width and a
BigIntmeet aBigDecimalunder the five operators, the comparisons and==, on either side and in chains, and in a compound assignment to aBigDecimal; a decimal literal beside one is one too (price + 0.01,0 < price < 20.0). Arealmeets one nowhere. A decimal literal is no pattern for aBigDecimal; compare with==. - Parts and conversions.
unscaled,scale,precision(the unscaled value’s digits, 1 for zero),sign,isZeroandabs.toBigInt,toLongandtoInttake the whole part, toward zero;toLongandtoInttrap withvalue out of range for long(orint) where it does not fit, andtoLongOptionandtoIntOptionanswerNone. - Text. A
BigDecimalis written in plain digits, never with an exponent:0.000001,1000000000000000000000. ItsDebugform is the same. Under%fthe precision is its places, rounded half to even, and with none it keeps its own; the flags+, space,0and#act as on areal. Like every number it is refused under%s, and as one never written with an exponent it is refused under%eand%g. - Identities.
BigDecimal.zero()andBigDecimal.one(), at scale 0.
Decimals meet a type that takes them
A type that implements the core trait FromDecimal takes every decimal number exactly, and with it
every integer and every BigInt. BigDecimal is the library’s one; a program’s own type joins by
implementing it beside FromInteger:
trait FromDecimal: FromInteger
static fromDecimal(text: string) -> Self
static fromBigInt(n: BigInt) -> Self
- A decimal literal where one is expected is its value, wherever a type is expected, as an
integer literal is for
FromInteger. It isT.fromDecimal(text), the text the literal as written with its sign and any exponent and without its separators (-1_000.5e-3passes"-1000.5e-3"), so no digit is rounded through areal. A type parameter bounded byFromDecimaltakes one the same way. - A
BigIntoperand beside one is converted to it, asT.fromBigInt(n), under the operators, the comparisons and==, on either side, as an integer operand is forFromInteger. A type that takes integers alone takes noBigInt. - A
realvalue is never converted, and a decimal literal is no pattern for such a type.
byte
byte is an octet with a value from 0 to 255. It is the element of binary data — file contents,
network buffers, encoded text — rather than a small number, so it has equality, ordering, the
bitwise operators &, |, ^ and ~, and shifts, but no arithmetic. int(b) gives its value
(0–255), and byte(n) makes one from an integer, trapping when n is outside 0–255. An integer
literal in a byte context must be in 0–255: val mask: byte = 0xf0.
real and char
real arithmetic follows IEEE 754, including NaN and signed zero; comparisons with NaN are false
except !=. x.isNaN, x.isInfinite (either infinity) and x.isFinite (neither) classify a
value, and each value is exactly one of NaN, infinite or finite. x.toInt and x.toLong are
int(x) and long(x), truncating toward zero, saturating at the bounds and mapping NaN to zero;
x.toReal is x. There is no implicit fused multiply-add. The square root, logarithms,
trigonometry and the other elementary functions are in the module
avin.math: math.sqrt(x).
x.toBits is the IEEE 754 binary64 encoding of x as a long, sign bit highest, and
real.fromBits(bits) the number of an encoding: 1.0.toBits is 0x3FF0000000000000, (-0.0).toBits
is long.MinValue, and the two are inverses for every encoding, a NaN’s payload included. Since
there is no single-precision type, binary32 is reached through its encoding, for a file format or a
wire protocol that carries one: real.fromBits32(bits: int) widens a binary32 exactly, and
x.toBits32 rounds x to the nearest binary32, ties to even, a magnitude past binary32’s greatest
finite value becoming an infinity and one below half its least subnormal a zero of the same sign.
A NaN narrows to a quiet NaN, keeping as much of its payload as the platform’s conversion does (on
ARM64 and x86-64, the top 22 bits), so a signaling binary32 NaN comes back from
real.fromBits32(b).toBits32 with its quiet bit set; every other binary32 comes back as it was.
main()
println(1.0.toBits == 0x3FF0000000000000) // true
println(real.fromBits(0x4000000000000000)) // 2
println(real.fromBits32(0x3DCCCCCD)) // 0.10000000149011612
println(0.1.toBits32 == 0x3DCCCCCD) // true
println(1e39.toBits32 == 0x7F800000) // true
true
2
0.10000000149011612
true
true
char supports ordering and equality but no
arithmetic; int(c) and char(n) convert.
A char has these methods, classifying by the Unicode Character Database:
| Method | Meaning |
|---|---|
isDigit | A decimal digit of any script (category Nd) |
isLetter | A letter of any script (categories Lu, Ll, Lt, Lm, Lo) |
isLetterOrDigit | isLetter or isDigit |
isWhitespace | A space separator other than the non-breaking ones (U+00A0, U+2007, U+202F), or U+0009 to U+000D, or U+001C to U+001F; this is not strip‘s test, which is the White_Space property and so counts U+00A0 |
isSpaceChar | A character of category Zs, Zl or Zp |
isUpper, isLower | Cased and upper, cased and lower |
isControl | U+0000 to U+001F and U+007F to U+009F |
displayWidth | The columns of a terminal it takes drawn on its own: 2, 1, or 0 (Display width) |
toUpper, toLower | The simple case mapping, one character for one: 'ß'.toUpper is 'ß' |
asDigit | The digit’s value in radix 36: a decimal digit of any script gives its value, an ASCII or fullwidth letter, either case, gives 10 to 35; any other character gives -1 |
string
string is a built-in value type with no identity: two equal strings are interchangeable, and
=== is not defined on them. It is immutable UTF-8.
string is a built-in type, not a class. It is final; its representation is its own, a length and its
bytes inline in one object; it gets its methods from the library through impl string; and it
conforms to traits through impl (Eq, Hash, Ord, Display). A type pattern s: string on an
Any matches it like any other type.
s.byteLengthis O(1). Iteration is bychar(s.chars) or by byte (s.bytes).- There is no
s(i)returning a char by index, because that would be O(n) behind O(1) syntax. Slicing takes byte offsets and traps on an offset that is not a character boundary. +concatenates two strings and nothing else. Other values reach text through interpolation (s"${x}") orx.toString(), both of which useDisplay.- Ordering is by code point, which for UTF-8 is byte order.
The library’s methods on string. Offsets and lengths count bytes and are int; a string holds at
most the largest int bytes. Every offset a search answers is one where a character begins, or the
end, so it can be given to charAt or slice again, and a search from an offset inside a
character never traps: it starts from the next character, or searching back, from the one the
offset is inside.
| Method | Result |
|---|---|
byteLength | The number of bytes, O(1) |
charCount | The number of characters, O(n) |
isEmpty, nonEmpty | Whether it has no bytes, or some |
startsWith(p), endsWith(p), contains(p) | Whether p occurs at the start, the end, anywhere; the empty string occurs in every string |
startsWith(p, at) | Whether p occurs at byte offset at; false when it would reach outside the string, and the empty string occurs only where a character begins or at the end |
byteAt(at), charAt(at) | The byte at offset at, and the character whose encoding begins there; each traps when at is outside the string, and charAt also when at is inside a character’s encoding |
slice(from, until) | The bytes from from up to until; traps unless 0 <= from <= until <= byteLength() and both offsets are character boundaries |
toUpper, toLower | Each character’s simple case mapping, one character for one, as char‘s methods of the same names map it: "straße".toUpper is STRAßE |
normalize(form), isNormalized(form) | The string in a Unicode normalization form, Nfc, Nfd, Nfkc or Nfkd, and whether it is in it already (Normalization) |
strip, stripLeading, stripTrailing | Without the Unicode White_Space characters at both ends, the start, the end |
trim | Without the characters up to U+0020, the ASCII controls and the space, at both ends |
repeat(n) | n copies joined; empty for zero; traps when n is negative |
replace(old, new) | Every occurrence of old, left to right and not overlapping, replaced by new; an empty old occurs nowhere |
indexOf(p), indexOf(p, from) | The byte offset of the first p, a string or a char, at or after from (default 0; below 0 counts as 0); -1 when there is none or from is past the end. The empty string is found at from, or at the next character when from is inside one |
lastIndexOf(p), lastIndexOf(p, end) | The byte offset of the last p, a string or a char, beginning at or before end (default byteLength); -1 when there is none. The empty string is found at end, at the start of the character end is inside, or at byteLength when end is past it |
indexWhere(f), indexWhere(f, from) | The byte offset of the first character satisfying f, at or after from; -1 when none does |
lastIndexWhere(f), lastIndexWhere(f, end) | The byte offset of the last character satisfying f that begins at or before end (default: the whole string); -1 when none does or end is below 0 |
head, last | The first and the last character; each traps on the empty string |
headOption, lastOption | Some of the first or the last character; None for the empty string |
stripPrefix(p), stripSuffix(s) | Without p at the start, without s at the end; the string unchanged where it is not there |
capitalize | With a lower-case first character mapped to upper case, and unchanged otherwise |
stripMargin(), stripMargin(c) | Each line with its leading characters up to U+0020 and the margin character after them (a vertical bar, or c) removed; a line whose first other character is not the margin is unchanged, and the line terminators stay |
chars | The characters, in order, as a Vector[char] |
bytes | The bytes of the encoding, in order, as a Vector[byte] |
utf8 | The bytes of the encoding in a new Array[byte], byteLength of them, which the caller owns: each call makes another, so writing to one changes neither the string nor any other. It is what a file, a socket or a request body is written from, and string.fromUtf8(s.utf8) is Ok(s) |
count(p) | The number of characters satisfying p |
split(sep) | The pieces between the occurrences of sep, as a Vector[string]; empty pieces are kept (",a,,b,".split(",") has five pieces), and a string without sep is one piece. An empty sep traps |
lines | The lines as a Vector[string], each ended by \n or \r\n and shown without it; a terminator at the very end starts no further line, so "a\nb\n".lines is two lines and "" has none. A \r not before \n stays in its line |
isBlank | Whether it has only White_Space characters, so the empty string is blank |
reverse | The characters in the opposite order |
padStart(w, c), padEnd(w, c) | At least w characters, c (default ' ') repeated before, after; w counts characters, not bytes, and a string already that long is unchanged |
padTo(n, c) | As padEnd(n, c), the name a sequence’s padding has |
displayWidth | The columns of a terminal it takes, cluster by cluster (Display width) |
padStartWidth(w, c), padEndWidth(w, c) | At least w columns of a terminal wide, c (default ' ') repeated before, after as often as it fits, and a space for a column a wide c leaves over; a string already that wide is unchanged, and a c that takes no column traps when padding is needed |
truncateWidth(w, e) | At most w columns wide: the string itself when it fits, or else as many whole clusters from the start as fit with the ellipsis e (default "…") after them; an ellipsis wider than w is left off, and a w of 0 or less keeps nothing |
equalsIgnoreCase(o) | Whether the two are equal after each character’s simple lower-case mapping |
take(n), drop(n) | The first n characters, all but the first n; n counts characters, not bytes, and is clamped to the string, so 0 or less takes none |
takeRight(n), dropRight(n) | The last n characters, all but the last n |
toInt(), toLong() | The number written in decimal: an optional - or +, then one or more ASCII digits and nothing else; a trap, For input string: "…", otherwise or when it does not fit the type |
toReal() | The number written as a decimal fraction, correctly rounded: an optional sign, digits with an optional point, an optional exponent (3.25, -.5, 1e10); a trap, as toInt‘s, for anything else, including white space, nan, inf, hexadecimal, and a number too large to be finite |
toIntOption(), toLongOption(), toRealOption() | Some of the number toInt, toLong or toReal reads, and None where it would trap |
toInt(radix), toLong(radix) | As toInt() and toLong() with digits of base radix, 2 to 36: 0–9, then a–z in either case; the same trap for text that is not such a number or does not fit, and a trap for a radix outside 2 to 36 |
toIntOption(radix), toLongOption(radix) | Some of the number the radix form reads, and None where its text would trap; a radix outside 2 to 36 still traps, being the caller’s mistake and not the text’s |
toBool(), toBoolOption() | true for the text true, false for false, exactly (no other case, no white space); toBool traps, as toInt does, on any other text and toBoolOption answers None |
map(f), flatMap(f) | A string of f applied to each character: f answers a char for map and a string for flatMap, and the results are joined in order |
filter(p), filterNot(p) | The characters that do, or do not, satisfy p, in order |
foreach(f) | Calls f on each character, in order |
exists(p), forall(p) | Whether some, or every, character satisfies p; false and true for the empty string |
find(p) | Some of the first character satisfying p, or None |
takeWhile(p), dropWhile(p) | The longest prefix whose characters all satisfy p, and the string without it |
span(p), partition(p) | A pair of strings: the longest prefix satisfying p and the rest; the characters that satisfy p and those that do not |
splitAt(n) | The pair of the first n characters and the rest; n is clamped as take‘s is |
tail, init | All but the first, and all but the last, character; each traps on the empty string |
charIterator() | The characters as an Iterator[char] that decodes one character for each next(), making no vector |
split(c), split(sep, limit), split(c, limit) | split with a char separator; and with at most limit pieces, the last holding the rest of the text with its separators. A limit of 0 or less sets none, 1 gives the whole string, and an empty string separator traps |
stripLineEnd | Without one \n or \r\n at its end; a lone \r, or no terminator, leaves it unchanged |
compareIgnoreCase(o) | The sign of the comparison after each character’s simple lower-case mapping: negative, zero or positive |
val word = "café"
println(s"${word.byteLength} ${word.charCount}") // 5 4
println(word.slice(3, 5)) // é
println(word.slice(0, 4)) // traps: offset 4 is inside `é`
A string has no length or size, since its length is counted in characters or in bytes, and
asking for one names both; nor does * repeat it, and the error names repeat:
word.length // string has no field `length`; a string counts its characters with `charCount` and its bytes with `byteLength`
word.toUpperCase // string has no field `toUpperCase`; a string maps its case with `toUpper` and `toLower`, as a `char` does
"-" * 3 // `*` needs two numbers of one type, not string and int; a string is repeated by `repeat`, as in `text.repeat(n)`
Strings from bytes
Bytes become a string through two static members
of string, which check that the bytes are UTF-8, since a string’s bytes always are:
| Static member | Result |
|---|---|
string.fromUtf8(bytes: Array[byte]) | Ok of the text the bytes encode, or Err of a Utf8Error |
string.fromUtf8Lossy(bytes: Array[byte]) | The text, with U+FFFD, the replacement character, in place of each maximal run of bytes that is not UTF-8: a sequence the bytes end inside is one replacement, a stray continuation byte another |
data Utf8Error(offset: long, truncated: bool) says where and why: offset is the byte offset at
which the first sequence that is not a character begins, and truncated is true where the bytes end
inside a sequence that more bytes could complete, and false where they hold one no continuation
could make a character. Refused are a continuation byte that begins nothing, an overlong encoding
(C0 AF for /), a surrogate (ED A0 80), a value past U+10FFFF (F4 90 80 80), a byte no
sequence begins with (FF), and a sequence cut short.
val bytes = "naïve".utf8
println(string.fromUtf8(bytes)) // Ok(naïve)
val cut: Array[byte] = [0x61, 0xE2, 0x82]
println(string.fromUtf8(cut)) // Err(Utf8Error(1, true))
println(string.fromUtf8Lossy(cut)) // a�
Normalization
The same text can be more than one sequence of characters: é is one character, U+00E9, or two,
e and the combining acute accent U+0301, and == compares characters, so the two are not equal.
s.normalize(form) puts a string in one of the four Unicode normalization forms (UAX #15), the
values of NormalizationForm, and s.isNormalized(form) says whether it is in that form already,
by the Unicode Character Database 17.0.0, the one char‘s methods answer from:
| Form | Meaning |
|---|---|
Nfc | NFC: canonical decomposition, then canonical composition. The form for storing and sending text |
Nfd | NFD: canonical decomposition, the combining marks in canonical order |
Nfkc | NFKC: compatibility decomposition, then canonical composition: fi is fi, ① is 1, a fullwidth A is A |
Nfkd | NFKD: compatibility decomposition, the combining marks in canonical order |
Hangul syllables compose and decompose by their algorithm; a code point unassigned in the database
is left as it is. A string of ASCII characters only is in all four forms and is returned at once,
unexamined. The compatibility forms discard distinctions, so they are for comparing and matching
rather than for storing. avin.crypto.saslPrep applies NFKC
as part of preparing a password.
main()
val composed = "caf\u{e9}"
val decomposed = "cafe\u{301}"
println(composed == decomposed) // false
println(decomposed.normalize(Nfc) == composed) // true
println(composed.normalize(Nfd).charCount) // 5
println("\u{fb01}le \u{2460}".normalize(Nfkc)) // file 1
println(composed.isNormalized(Nfc)) // true
println(decomposed.isNormalized(Nfc)) // false
false
true
5
file 1
true
false
Display width
displayWidth is the number of columns of a terminal, in a fixed-width font, a character or a
string takes, which is what lines text up in a table or a help screen; charCount is not, since a CJK
ideograph takes two columns and a combining accent none. A character on its own takes:
- 2 when it is East Asian Wide or Fullwidth: CJK ideographs, kana, Hangul syllables, fullwidth forms,
and the emoji shown as pictures by default (
'😀'); - 0 when it is a nonspacing or enclosing mark (a combining accent, a variation selector), a format character (the zero-width space and joiner, the bidirectional marks), or a Hangul vowel or final that joins the syllable before it; the soft hyphen and the marks written before a number are shown, and take 1;
- 0 when it is a control character, U+0000 to U+001F and U+007F to U+009F, tab and newline included: where one moves the cursor is the terminal’s business, not a width;
- 1 otherwise, the East Asian Ambiguous characters and unassigned code points included.
A string is measured cluster by cluster, as a modern terminal draws it. A cluster is a character with
the zero-width characters after it, a skin-tone modifier after an emoji, and, when it is a
pictograph, each pictograph a zero-width joiner joins to it. A cluster is as wide as its first
character, except that a variation selector 16 after an emoji makes it 2 (❤️, the keycap 1️⃣), a
skin tone makes an emoji 2, and two regional indicators are one flag of 2. A control character is a
cluster of its own. The table is the Unicode Character Database’s, version 17.0.0.
"hello".displayWidth // 5
"日本語".displayWidth // 6
"e\u{301}".displayWidth // 1: an e and a combining acute
"👩🏽💻".displayWidth // 2: a skin tone and a joined pictograph
"日本".padEndWidth(6) + "|" // 日本 |
"日本語テキスト".truncateWidth(7) // 日本語…
A formatted field’s width counts these columns too, so f"${name}%-10s" lines up whatever name
is written in (Strings and formatting).
unit
unit has the single value (). It is an ordinary type: it can be a type argument, a field, a
parameter, and a pattern. A function whose body is an indented block with no = and no result type
returns unit.
Tuples
(A, B, …) is a tuple type of any arity, written and matched with parentheses: (1, "one"),
(n, name) -> …. Elements are read with t.0, t.1, numbered from 0; asked for t._1 or
t._2, the error names the part to write ((string, int) has no field `_2`; a tuple's parts are numbered from 0, so write `.1` ). Tuples are values with no identity and derive
Eq, Hash, Ord, Display and Debug when their elements do. A pair has swap, the pair
with its parts the other way round: (1, "one").swap is ("one", 1). A program adds methods to
tuples with an impl naming a tuple type built from its parameters,
impl[A, B] (A, B) or impl[A] (A, A); only the core library implements a trait for tuples.
Where a value fills the rest of a line, a tuple needs no parentheses: after = in a function, clause
or binding, after return, after -> in a match arm, and as a line of a block, including its
last. Inside brackets and in the body of a one-line if or while, a comma separates other things,
so a tuple there is parenthesized, a match arm’s one-line body inside brackets
included, and so is the last line of a block, a lambda’s
body, when that line closes a bracket opened before the block
(continuation lines).
divmod(a: int, b: int) -> (int, int) = a / b, a % b
bounds(a: int, b: int) -> (int, int)
if a > b then return b, a
a, b
A tuple is taken apart by a binding (val q, r = divmod(17, 5), val (a, (b, c)) = t), by a
multiple assignment, by tuple
patterns in match and in clauses, and by a lambda’s parameters.
Where a function of one parameter whose type is a tuple of n elements is expected, n at least two, a lambda of exactly n parameters takes the tuple apart: its parameters are the tuple’s elements, in order, each typed from its element. A lambda of one parameter takes the tuple whole, as it would anywhere.
val xs = [1, 2, 3]
xs.zip(xs).forall((x, y) -> x == y) // true
xs.zip(["a", "b", "c"]).map((n, s) -> s"$s$n") // [a1, b2, c3]
[((1, 2), 3)].map((p, z) -> p.0 + p.1 + z) // [6]: an inner tuple is one element
map.filter((k, _) -> k != "skip")
- A parameter written with a type takes an element of that type, or of a narrower one as any
lambda’s parameter may, and its body sees the type written:
(a: Animal, n) -> …over(Dog, int)pairs. A declared type the element does not fit is an error naming the element. - An element the expected type leaves unknown, as in a generic function’s
((A, B)) -> CwhoseAandBnothing else fixes, takes its type from the parameter’s declaration; one with neither is an error asking for the type. _takes an element and binds nothing. Each parameter is aval, as any lambda’s is.- It applies only where the lambda’s parameters are not as many as the expected function’s: a
lambda of two parameters where
(A, B) -> Cis expected takes two arguments. Among overloads, a candidate that has a lambda take a tuple apart is chosen only where no candidate takes it as written, soMap‘smap((k, v) -> (v, k))is its(K, V) -> (L, W)overload. - A lambda whose parameters are as many as neither the function’s nor the tuple’s elements is an
error naming both shapes:
expected a function of 1 parameter, (int, int), but this lambda takes 3: a lambda takes that tuple as one parameter or as 2 parameters, one for each element.
A match function, match (x, y) -> …, still
takes a tuple apart by a pattern, for shapes a list of names cannot write: nested tuples, literals,
variants.
Function types
(A, B) -> C is the type of a function taking A and B and returning C; () -> C takes nothing.
A function taking one parameter may drop the parentheses: int -> string, Option[T] -> bool.
(A) -> B and A -> B are the same type. -> groups to the right, so int -> int -> int is
int -> (int -> int), a function returning a function; a function taking a function writes the
parameter in parentheses, (int -> int) -> int. A tuple parameter takes a second pair of
parentheses, ((A, B)) -> C, since (A, B) -> C takes two parameters.
twice(f: int -> int, x: int) -> int = f(f(x))
adder(n: int) -> int -> int = x -> x + n // the result is a function type
val fs: List[int -> int] = [adder(1), adder(2)]
val add: int -> int -> int = a -> b -> a + b
The form works wherever a type does: parameters, fields, results, type arguments, tuple parts,
val annotations and supertypes. A result of function form needs no parentheses, since the
declaration’s = ends it. A type pattern in a match arm is the exception: the arm’s -> follows
the type, so a function type there is written in parentheses, f: (int -> int) -> body.
Compiler messages print every function type with a parameter list, (int) -> int.
A by-name parameter type is written -> T inside a parameter list; see
call-by-name. Function types are traits: a class or trait may list a function type
among its parents after :, and a data type or class may name one in an impl, and its values are
then subtypes of that function type, callable as value(args) and usable wherever it is expected,
with no conversion. Such a type has an apply taking exactly the function type’s parameters and
yielding its result or a subtype, and a call of the value as a function runs that apply.
class Shout: (string) -> string
apply(s: string) -> string = s + "!"
data Lengths(extra: int)
impl (string) -> int for Lengths
apply(s: string) -> int = s.charCount + extra
val f: (string) -> string = Shout()
["a", "b"].map(Lengths(1)) // [2, 2]
A function type in a parent list follows the variance rules of any parent: its parameters are
contravariant positions and its result a covariant one. A type is at most one function type,
counting those its superclass and traits are, and a built-in type is none. The core library’s
collections are functions this way: a Seq[T] is an (int) -> T, a Set[A] an (A) -> bool and a
Map[K, V] a (K) -> V (see collections).
There is no arity limit.
Functions compose. The core library adds to every function of one parameter f.andThen(g), the
function that runs f and then g on its result, and f.compose(g), which runs g first; and to
every function of two parameters f.tupled(), the function taking its two arguments as one pair. A
function type is a trait, so they reach every value that is a function of that shape: a lambda, a
reference to a function, a method value (of a method declared with a parameter list, one declared
with an empty list () only where a function type is expected; a
parameterless method has none, and () -> x.head is the
function that reads one), and a value of a type naming a function type, a sequence or a map among
them. A type’s own method of the same name and parameter types is found first.
identity, in the prelude, is the function that gives back its argument, for passing where a
function is asked for and nothing should change.
val inc = (x: int) -> x + 1
inc.andThen(x -> x * 2)(3) // 8
inc.compose((x: int) -> x * 2)(3) // 7
((a: int, b: int) -> a + b).tupled()((2, 3)) // 5
[1, 2, 3].andThen(n -> n * 10)(0) // 10: a sequence is a function of its index
[[1], [2, 3]].flatMap(identity) // [1, 2, 3]
A program may add methods to function types the same way, with an
impl naming one: impl[A] (A) -> A, impl[A, B, C] (A, B) -> C. A
@sendable (A) -> B there adds only to @sendable functions.
@sendable before a function type, @sendable (A) -> B, makes the type of a function that may
run on any thread: it captures only sendable values and no var, and the code it runs reaches no
module-level mutable state (threads). Such a type is Sendable, and
a plain function type is not, since it does not say what its values capture. Only a function type
may be marked; @sendable int is an error. A @sendable (A) -> B is a (A) -> B, with no
conversion, so it is passed wherever the plain type is expected and a vector of them is a vector of
the plain type; a plain function value is not a @sendable one. A lambda, a reference to a function
and a method value written where a @sendable function type is expected are made as one, and are
checked there as a thread’s body is. Inside a function, a parameter marked
@sendable that takes a function holds a @sendable function.
val step: @sendable (int) -> int = (x) -> x + 1 // checked: captures nothing
val named: @sendable (int) -> int = double // checked: what `double` reaches
val plain: (int) -> int = step // a @sendable function is a plain one
val back: @sendable (int) -> int = plain // error: `plain`'s type does not say what it captures
adder(n: int) -> @sendable (int) -> int = (x) -> x + n
Two overloads that differ only in whether a function parameter is @sendable are the same
overload, as two that differ only in a by-name parameter are, since one lambda may be passed for
either. An override takes the parameter types of the method it overrides, the mark included, and
may yield a @sendable function where that method yields the plain type. Messages print the mark
as it is written, @sendable (int) -> int.
Placeholder lambdas
A call’s argument that holds _ is a lambda: each _ is a parameter of its own, in the order
written, and the argument is the body. A val or var with a declared type takes one the same way,
as does the body of a function with a declared result type, and each of its clauses’ bodies.
xs.map(_ + 1) // xs.map(x -> x + 1)
people.map(_.name) // people.map(p -> p.name)
xs.filter(0 < _ < 10) // xs.filter(x -> 0 < x < 10)
xs.reduce(_ + _) // xs.reduce((a, b) -> a + b)
people.sortBy(_.age)
xs.map(scale(_, 2)) // xs.map(x -> scale(x, 2))
orders.map(_.items.map(_ * 2)) // orders.map(o -> o.items.map(x -> x * 2))
val inc: (int) -> int = _ + 1
adder(n: int) -> (int) -> int = _ + n
-
A branch is a place of its own. Where an
if, amatchor a block stands in one of these places, each branch of theif, each arm of thematchand the block’s last line is a place in turn, with the same rules, so a choice of functions reads as one:val key: (Request) -> string = by match "method" -> _.method "status" -> _.status.toString() _ -> _.path xs.map(if up then _ + 1 else _ - 1)The condition, the subject, a guard and a block’s earlier lines keep their own
_, and so do aniformatchanywhere else:val f = if up then _ + 1 else 0, with no declared type, is an error, and so is a function’s body with no declared result. A branch may be a written lambda or any other value of the function type beside the placeholder ones. -
The lambda is the nearest argument holding the
_. A_is found through operators of every precedence, member access and method calls on it, tuple parts ((_, 0)),is, a range’s bounds,with‘s base and a call’s callee, so_.name.byteLength + 1is one lambda. Another call’s argument is a lambda of its own: inorders.map(_.items.map(_ * 2))the first_is an order and the second an item. A name ending in:is written after its argument, so in_ +: _the first_is the element. -
A
_that is a whole argument belongs to the argument around its call:xs.map(scale(_, 2))isxs.map(x -> scale(x, 2)), andapply2(scale(_, 2) + _)isapply2((a, b) -> scale(a, 2) + b). A lambda that would only call a named function with its parameters in order,xs.map(double(_)), is that function: it is an error saying to passdouble. A constructor’s name is no function’s, soxs.map(Some(_))isx -> Some(x). -
A lambda, a block, an
if, amatch, a collection literal and an interpolation keep their own_: none of them is searched from around it, soxs.map(n -> n + _)is an error, as is any_outside the places above,val y = x + _; only anif‘s branches, amatch‘s arms and a block’s last line pass a place on. A_alone as a whole argument of a call that is itself no argument,scale(_, 2)as a statement, is an error too. -
The parameters take their types from the function expected, as any lambda’s do, and their count must be its parameter count; a lambda of two
_s where a function of one tuple is expected takes the tuple apart, soxs.zip(ys).map(_ + _)adds the pairs. A count that fits neither is an error naming both counts, and a_whose type nothing gives is an error asking for the lambda to be written out with a type. Overloads see the lambda as they see one written out: the number of_s picks among overloads of different counts. -
Each
_is used once, so a parameter read twice, or a parameter not read at all, is written as an ordinary lambda.
The other meanings of _ are unchanged: a parameter _ -> or (_, b) -> binds nothing, a
pattern’s _ matches anything, val _ =, a discarded part q, _ = …, for _ in, a clause’s _
argument, the last guard | _ =, the digit separator in 1_000, and a name that begins with _,
such as _offset, which is an ordinary name.
Partial functions
PartialFunction[-A, +B] is a core-library trait, and a subtype of A -> B: a function defined at
some values of A and not others. isDefinedAt(a) says whether it is defined at a; calling it,
pf(a), at a value it is not defined at traps, and the trap names the program’s call. lift() is
the total function A -> Option[B], None where it is not defined; applyOrElse(a, default) is its
value at a, or default(a) where it is not defined; pf.orElse(other) is pf where it is
defined and other elsewhere. A match with nothing before
it, written where a PartialFunction is
expected, makes one:
val half: PartialFunction[int, int] = match n if n % 2 == 0 -> n / 2
half.isDefinedAt(3) // false
half.applyOrElse(3, n -> n) // 3
[2, 4].map(half) // [1, 2]: a partial function passes where `int -> int` is expected
Vector types
[]T is another way to write Vector[T]: the same type, in any position a type may stand.
xs: []int, [][]int (a Vector[Vector[int]]), Option[[]string] and ([]int, string) all work,
and a program’s entry point may be main(args: []string). The element is a name or a parenthesized
type, so []int -> int is a function taking a vector, ([]int) -> int, and [](int -> int) is a
vector of functions. A type pattern in a match arm takes the form without parentheses,
v: []int -> body. There is no fixed-length [N]T; [3]int is an error, and Array[T] is the
fixed-length contiguous collection. Compiler messages print the type as Vector[int].
Any and Nothing
Any is the top type. Every reference type is a subtype of Any. A value type (built-ins, tuples,
data) converts to Any by boxing at the point of conversion; the box records the exact type, so a
match on an Any recovers the value.
describe(x: Any) -> string = x match
s: string -> s"text $s"
n: int -> s"number $n"
_ -> "something else"
describe(42) // the int is boxed where it becomes an Any
A value converts to Any wherever one is expected of it, at a single site: an argument, a binding,
an assignment, a field, a result, a part of a tuple written out, or each branch of an if or
match expected to yield an Any. A tuple already made converts only where each part already is
what the wider tuple holds there: a part that is an object (a string, a data value, a tuple, an
instance of a class) is its own Any, so a (string, int) is a (Any, int), and so is a (P, int)
for a data type P. A part that would need a box does not convert, since its layout differs and
boxing never happens inside a value already made: an (int, int) is not an (Any, int), nor is a
(bool, int). A tuple written out where the wider one is expected, (n, 1), boxes its part there.
How a value is boxed is the compiler’s choice, and invisible except in cost. A string, a tuple and a
data value are already objects whose header names their exact type, so they need no box; a
number, a char, a bool and unit get one. A tuple’s type at run time is the type it was made
with: (animal, 1) with animal: Animal is an (Animal, int), whatever class the animal is.
A value of a built-in type or a tuple converts the same way to a trait it implements, at the same
sites: val shown: Vector[Display] = [1, "two", (3, 4)], describe(d: Display) called as
describe(42). Calls through the trait reach the type’s own implementation, and a type pattern
recovers the value: d match n: int -> …. An overload taking the value’s own type is more specific
than one taking a trait it implements.
== and != on an Any are decided at run time by the values’ own types: values of one type
compare as that type does, by value or by identity, and values of different types are unequal (see
equality). === and !== need a side whose type is a class,
since an Any may hold a value with no identity: x === obj is defined, and x === y with both
Anys is an error (see identity). A type pattern recovers the
value’s type, and with it the other comparisons that type has.
Nothing is the bottom type: the type of return, break, continue and a call to a function that
never returns. It is a subtype of every type, and an expression of type Nothing never produces a
value. An empty collection literal or None does not have a Nothing type argument; its type
comes from context (see inference).
A function’s result is a covariant position, so a function whose result is Nothing is a function
of every result type: a named function, a lambda, a method value or any other value of type
(A) -> Nothing may be used where an (A) -> R is expected, and so may a () -> () -> Nothing where
a () -> () -> R is. It converts where it is written, in a declared type, an argument (also one
whose parameter type the other arguments decide), a result, a field, and the branches of an if or
match or the elements of a collection literal, which agree on the other function type; the value
is evaluated once, there. Its parameters still vary as a function’s do: an (Animal) -> Nothing is a
(Dog) -> string, and a (Dog) -> Nothing is no (Animal) -> string. Inside another type it is
not converted, as a value of a value type is not: a Vector[(int) -> Nothing] is no
Vector[(int) -> int] (proposed).
refuse(x: int) -> Nothing = fail(s"refused $x")
val f: (int) -> Option[int] = refuse
val g = if strict then refuse else (x: int) -> Some(x) // (int) -> Option[int]
Union types
A | B is a value of A or of B, written in annotations and never inferred, made at a single
site as an Any is, and taken apart by a match that covers every member. ? uses it to pass on
errors of several types: a function yielding Result[T, IoError | ParseError] may ? either kind.
| binds more tightly than ->, so (A) -> B | C returns a union. The rules are in their own
chapter, union types.
describe(x: int | string) -> string = x match
n: int -> s"number $n"
s: string -> s"text $s"
Type ascription
(value: T) gives a value the type T where it is written, with no conversion and no val to
hold it. It is checked exactly as the value of val x: T = value is, and the expression is of type
T:
- A literal takes
T:(3_000_000_000: long),(255: byte),(2.5: real),(1: real), and any integer literal of any size for a type that takes integers ((123456789012345678901234567890: BigInt),(7: Cents)) and any decimal literal for one that takes decimals ((0.1: BigDecimal)). In an operation the ascribed operand decides the other’s type:(1: long) + 2147483647is along. - A value whose type its context decides is decided by
T:(None: Option[string]),([]: List[int]),({}: Map[string, int]),(Ok(3): Result[int, string]), and a lambda,((x -> x * 2): int -> int), whose parameters takeT‘s. - A value of a subtype stands as one of
T:(dog: Animal),(Square(3): Shape),([1, 2]: Iterable[int]),(Some(dog): Option[Animal]), and a member of a union as the union,(n: int | string)(union types).(x: Any)is the value as anAny. - Nothing else is accepted. An ascription never narrows (
(animal: Dog),(u: int)of anint | string: test the value withisormatch) and never converts:(n: long)of anintnis an error that says to writelong(n),(k: BigInt)of an integer variable saysBigInt(k), arealis noBigDecimal, and a value of an unrelated type is refused. A literal that does not fit is refused as it is in a declaration:(300: byte).
It is written as an item of a parenthesized list, so the : never meets another meaning: a group,
(n: long); a tuple’s part, (1: long, "a"); a call’s argument, f(None: Option[string], x), the
value of a named one included, f(k = 1: long). The value before : is a whole expression and the
type after it a whole type, a function type included: (a + b: long), (f: int -> int). A
parenthesized list followed by -> is a lambda’s parameters, (n: long) -> n. A name followed by
: int -> body whose rest is no type is a lambda whose typed parameter lacks its parentheses, and
is reported so. At the start of a block’s line, name(x: T) followed by =, ->, an indented
block or a line of clauses declares a local function, as it always has; a call there with a name
ascribed is written with the ascription grouped, retry((n: long)), and a call followed by nothing
is a call, so show(n: long) on two lines calls show twice.
In a placeholder lambda, (_: T) is a parameter of type T:
twice((_: long) * 3, 1) passes (x: long) -> x * 3.
val big = (123456789012345678901234567890: BigInt) * 2
val none = (None: Option[string])
println(total(([1, 2, 3]: Iterable[int])))
println(describe((7: int | string)))
val n = 3
val m = (n: long) // error: an ascription converts nothing; write `long(n)`
Reference types and value types
Class instances, objects, arrays, buffers, closures and boxes are reference types: they live on
the garbage-collected heap and have identity. Built-in types, tuples and data types are value
types: they have no identity, and the compiler chooses their representation. See
equality, identity and memory.