Chapter 1 took a quick tour of Nex through four complete programs. This chapter starts again at the beginning and goes slowly. It looks carefully at values: what kinds of values exist in Nex, how variables give them names, and what happens when you need to convert one kind into another.
Every value in Nex has a type. A type is a classification that determines two things: what the value represents, and what operations are valid on it. The number 42 and the string "42" look similar in print, but they are different kinds of thing. You can multiply 42 by two. You cannot multiply "42" by two. The type is what makes this distinction precise.
Nex’s basic scalar types are:
Integer — whole numbers, positive or negative: 0, 42, -7, 1000000Real — numbers with a fractional part: 3.14, -0.5, 1.0, 2.718Boolean — the truth values true and falseString — sequences of characters enclosed in double quotes: "hello", "42", ""Char — a single character: #a, #Z, #65These types cover the vast majority of what you will need in the early chapters. Integer is a 64-bit integer with checked arithmetic, and Real is an IEEE-754 double; both are documented in Appendix B.
A variable is a name for a value. let introduces a new variable and gives it its first value:
nex> let x := 10
10
nex> let y := x + 5
15
nex> x + y
25
The := symbol is read “becomes”: after let x := 10, the name x refers to the value 10. Once a variable exists, give it a new value with := alone, without let:
nex> x := 20
20
nex> x
20
let introduces a name; plain := changes the value of a name that already exists. Assigning to a name that was never introduced is an error:
nex> total := 5
Error: Cannot assign to undefined variable: total
The REPL is forgiving in the other direction. A second let x := ... simply replaces the earlier x, so you can redefine things freely while experimenting. A program in a file is stricter: declaring the same name twice in the same block is an error. Use let once for each variable and plain := after that.
Variable names are case-sensitive, so x, X and total_cost are three different names. By convention, names use lowercase letters with underscores between words: total_cost, start_location, item_count. At the REPL, :vars lists every variable you have defined, with its current value.
An integer is a whole number. Integer arithmetic in Nex works as you would expect for addition, subtraction, and multiplication:
nex> 10 + 3
13
nex> 10 - 3
7
nex> 10 * 3
30
Division between two integers deserves attention. When you divide one integer by another using /, the result is always an integer — the fractional part is discarded:
nex> 10 / 3
3
nex> 7 / 2
3
This is called integer division. It is not a mistake; it is the defined behaviour for the / operator on integers. The % operator gives the remainder:
nex> 10 % 3
1
nex> 7 % 2
1
Together, / and % give you full information: 10 / 3 is 3 remainder 1. If you want a fractional result, use Real values instead — Section 2.4 covers this.
Integer literals can also be written in binary, octal or hexadecimal, using the prefixes 0b, 0o and 0x. An underscore may separate digits to make long numbers easier to read:
nex> 0b1010
10
nex> 0o17
15
nex> 0xFF
255
nex> 1_000_000
1000000
These are different ways of writing the same Integer values: 0xFF and 255 are the same number. The prefixes must be lowercase, but the hexadecimal digits may be in either case.
Integers also have methods. Methods are operations invoked with dot notation:
nex> (-7).abs
7
nex> 3.max(8)
8
nex> 3.min(8)
3
The abs method returns the absolute value. The max and min methods return the larger and smaller of two values respectively. These are the same operations as arithmetic, just written differently — the dot notation makes explicit that the operation belongs to the value on its left.
Nex also provides bitwise operations on Integer values. These are mainly useful for low-level work such as flags, masks, encodings, and compact state representations. The interface uses method names rather than symbolic operators:
nex> 5.bitwise_left_shift(1)
10
nex> 6.bitwise_and(3)
2
nex> 5.bitwise_is_set(0)
true
Bitwise operations use 32-bit integer semantics; Appendix B lists the full set of methods.
One method worth knowing early is pick:
nex> 6.pick
4
pick returns a random integer in the range from zero up to but not including the value it is called on. 6.pick returns a random integer from 0 to 5. The result will differ each time you call it. This is useful for simulations and exercises, and we will use it in several places later on. (When a program needs the same random numbers on every run, say to repeat a simulation exactly, the math/Random library makes them from a seed; see Appendix C.)
Most programs never need to care how many bits an integer occupies: Integer is a 64-bit value, which is plenty. (Integer64 is another name for the same type.) Programs that read files or parse network messages sometimes do care, because the data they handle has an exact width. For those, Nex has three more integer types:
Byte — 8 bits, unsigned, from 0 to 255Integer16 — 16 bits, signed, from -32768 to 32767Integer32 — 32 bits, signed, from -2147483648 to 2147483647Each is a type of its own. You write a value of one by adding a suffix to an integer literal — u8 for a Byte, i16 for an Integer16, i32 for an Integer32:
let b: Byte := 200u8
let port: Integer16 := 8080i16
let offset: Integer32 := -70000i32
print(b) -- 200
print(port) -- 8080
print(offset) -- -70000
A literal without a suffix is always an Integer, so let b: Byte := 200 is a type error. Unary minus keeps the type of a signed value, which is why -70000i32 is an Integer32; the minimum, -32768i16, can be written too, although 32768i16 is out of range. The suffix letters are u8, not b, because b is also a hexadecimal digit: 0xFFu8 is a Byte, and 0x1b is just a number.
These types never turn into one another — or into Integer — on their own. This is deliberate: silently mixing widths is a classic source of bugs. To move between them, call a conversion method. Converting to a narrower type checks that the value fits, and raises an error if it does not:
let n: Integer := 300
let small: Integer16 := n.to_integer16() -- fine
print(small) -- 300
print(n.to_byte()) -- error: 300 is not in 0..255
Arithmetic on these types gives an Integer, so the result cannot overflow the narrow type. If you want a narrow value back, convert it, and that conversion is where the range is checked:
let a: Byte := 100u8
let total: Integer := a + a -- 200, an Integer
let doubled: Byte := (a + a).to_byte()
print(doubled) -- 200
Comparison works between two values of the same type; to compare a Byte with an Integer, convert one of them first (b.to_integer()).
Bytes appear naturally when you work with text. to_bytes() gives the UTF-8 encoding of a string as an Array[Byte], and create String.from_bytes(...) turns it back:
let bytes: Array[Byte] := "café".to_bytes()
print(bytes) -- [99, 97, 102, 195, 169]
print(create String.from_bytes(bytes)) -- "café"
Appendix B lists the methods of each type, and Appendix C describes Byte_Array, a compact buffer for large amounts of binary data.
A Real value is a number with a fractional part. Write real literals with a decimal point:
Nex requires at least one digit after the decimal point. So 10.0, .5, and 12.0e-3 are valid real literals, but 10. and 12.e-3 are not.
nex> let pi := 3.14159
nex> pi * 2.0
6.28318
Arithmetic on real numbers works as expected and always produces real results:
nex> 10.0 / 3.0
3.3333333333333335
nex> 7.0 / 2.0
3.5
Note the trailing digits in the first result. Real numbers in Nex, as in most programming languages, are represented internally as binary floating-point values. Most decimal fractions cannot be represented exactly in binary, so what you get is the closest representable approximation. For most purposes this is fine. For money and other quantities that must be exact, work in the smallest whole unit — for example, track amounts in integer cents rather than fractional dollars.
The round method converts a real number to the nearest integer:
nex> 3.6.round
4
nex> 3.2.round
3
To show a real number with a set number of decimal places, use format. It rounds the number and gives back a string with exactly that many digits after the point:
nex> (10.0 / 3.0).format(2)
"3.33"
nex> 2.5.format(2)
"2.50"
Because the result is a String, it is for display. Keep calculating with the Real itself.
Real numbers also have abs, min, and max:
nex> (-3.5).abs
3.5
nex> 1.2.max(4.7)
4.7
A Boolean value is either true or false. Booleans arise from comparisons:
nex> let x := 10
nex> x > 5
true
nex> x = 5
false
nex> x /= 5
true
In Nex, = tests equality and /= tests inequality. (The := you have been using is assignment — a different operation entirely.)
Booleans can be combined with and, or, and not:
nex> true and false
false
nex> true or false
true
nex> not true
false
nex> x > 5 and x < 20
true
The and operator returns true only when both sides are true. The or operator returns true when at least one side is true. The not operator inverts a boolean value.
A String is a sequence of characters. String literals are enclosed in double quotes:
nex> let greeting := "Hello, Nex"
nex> greeting.length
10
The length method returns the number of characters in the string.
Strings can be searched and inspected:
nex> greeting.contains("Nex")
true
nex> greeting.starts_with("Hello")
true
nex> greeting.index_of("N")
7
index_of returns the position of the first occurrence of its argument, counting from zero. If the argument is not found, it returns -1.
Substrings are extracted with substring, which takes a start index (inclusive) and an end index (exclusive):
nex> greeting.substring(0, 5)
"Hello"
nex> greeting.substring(7, 10)
"Nex"
Case conversion:
nex> greeting.to_upper
"HELLO, NEX"
nex> greeting.to_lower
"hello, nex"
Whitespace removal:
nex> let padded := " hello "
nex> padded.trim
"hello"
Splitting a string into parts:
nex> let csv := "one,two,three"
nex> csv.split(",")
["one", "two", "three"]
split returns an array — we will work with arrays in Chapter 9.
A single character has a type of its own, Char. A character literal is written with a # in front. #a is the letter a, and #65 is the character whose Unicode code point is 65, which is A:
nex> #a
#a
nex> #65
#A
nex> #10024
#✨
nex> "Nex".char_at(0)
#N
The numeric form is useful for characters that are hard to type. #10 is the newline character, which the word counter in Chapter 1 used to count lines, and #10024 is the sparkles emoji, if your terminal can show it. char_at(i) gives the character at position i of a string. A Char is not a one-character String: #a and "a" are values of different types, and #a = "a" is false.
You have now seen two ways to express the same operations. Addition can be written as 7 + 5 or as 7.plus(5). Comparison can be written as x > 5 or as x.greater_than(5). Both forms produce identical results.
nex> 7 + 5
12
nex> 7.plus(5)
12
nex> 10 > 3
true
nex> 10.greater_than(3)
true
The operator form is shorter and more familiar. The method form is more explicit about what is happening: 7.plus(5) makes visible that plus is an operation that belongs to the value 7, and that 5 is its argument. In most situations you will use operators. When working with generic code, the method form becomes necessary. For now, use whichever is clearer.
When you write let x := 10, Nex infers that x is an Integer from the value on the right-hand side. Type inference is convenient, but writing the type explicitly is better practice:
nex> let x: Integer := 10
nex> let name: String := "Ada"
nex> let height: Real := 1.52
nex> let enrolled: Boolean := true
The annotation — the : Type after the variable name — makes your intention explicit. It means the variable is expected to hold a value of that type, and if you later accidentally assign the wrong type, Nex can tell you immediately. Type annotations also serve as documentation: a reader of your code knows what kind of value a variable holds without having to trace where it came from.
In the REPL, annotations are optional. In functions and class definitions — which we reach in Chapters 6 and 12 — they are required on parameters and return types. Building the habit now means less adjustment later.
Programs in files are checked more strictly than REPL input. When you run a file with nex, or compile it with nex compile jvm, the whole program is type-checked before any of it runs. That is why the programs in this book annotate their top-level variables: the annotations tell the checker, and the reader, exactly what each variable is meant to hold. At the REPL you can turn the same checking on with :typecheck on, and off again with :typecheck off.
Nex does not convert between types automatically in general. Each scalar type provides conversion methods for cases where you need to change representation. The main exception you have already seen is string concatenation with +: if either operand is a string, the other operand is converted with to_string internally.
Converting a number to a string:
nex> let age: Integer := 25
nex> "Age: " + age
"Age: 25"
Because the left operand is a string, Nex performs string concatenation and converts age by calling its to_string method internally. Writing age.to_string explicitly is still valid when you want to make the conversion obvious.
Converting a string to a number:
nex> let s: String := "42"
nex> let n: Integer := s.to_integer
nex> n + 8
50
Real conversion works the same way:
nex> "3.14".to_real * 10 * 10
314.0
The conversion methods only work when the string actually represents a value of the target type. Calling .to_integer on a string that does not contain a valid integer raises an exception:
nex> "hello".to_integer
Error: Not a valid number
The string "hello" does not represent an integer, and there is no sensible integer value for Nex to return. The error fires immediately, at the point of the conversion, so you know exactly where the problem is. We return to error handling in Chapter 21; for now, the rule is simple: only call .to_integer and .to_real on strings you know contain valid numbers.
Every variable introduced so far holds a definite value. Nex enforces this by default: a variable of type Integer must hold an integer; it cannot hold “nothing.” This guarantee is one of the most practical features of a typed language. It means that whenever you use a variable, you know it has a value.
Occasionally, however, a variable genuinely might not have a value — perhaps it represents a search result that might come back empty, or a field that has not yet been set. For these cases, Nex provides detachable types, written with a leading ?:
nex> let maybe_name: ?String := nil
nex> maybe_name
nil
A detachable type can hold either a value of the declared type or nil. Before using a detachable variable, you must check that it is not nil:
nex> if maybe_name /= nil then
print(maybe_name.length)
end
This check is not optional. Calling a method on a nil value would produce an error, and Nex requires you to guard against it. The ? in the type annotation is a signal to both the programmer and the system: this variable might be nil, and code that uses it must account for that possibility.
For most variables in early chapters, you will not need detachable types. They become more important when working with class fields and collections, which we reach in Chapters 12 and 9 respectively.
Note: You can use the ?. safe-access operator for reading a field through a detachable reference — maybe_name?.length evaluates to nil if maybe_name is nil, and to maybe_name.length otherwise, without a separate guard.
All the programs so far have been self-contained — they produce output but never ask the user for anything. Reading input goes through the console, a Console object that every Nex program and REPL session already has under the name console. You do not declare it; it is predeclared, as if each program began with
let console := create Console
The create keyword is how all objects are constructed in Nex; Chapter 12 explains it fully. For now, just use console. (You cannot assign a new value to it, but you may declare your own variable named console, which then hides the predeclared one.)
The read_line method reads a line of text from the user and returns it as a string:
nex> console.print_line("What is your name?")
What is your name?
nex> let name := console.read_line
At the read_line call the program pauses and waits. Type your name and press Enter. Then:
nex> console.print_line("Hello, " + name + "!")
Hello, Ada!
Notice console.print_line rather than the bare print. Both write output, but they write it differently. print shows a value the way the REPL does, so a string appears in quotes. print_line writes just the text and ends the line. Use print for quick checks, and print_line for messages meant for people.
Here is the complete interactive program as you would enter it at the REPL:
nex> console.print_line("Enter your age:")
Enter your age:
nex> let input := console.read_line
nex> let age: Integer := input.to_integer
nex> let birth_year: Integer := 2026 - age
nex> console.print_line("You were born around " + birth_year.to_string)
You were born around 2000
This small program touches everything introduced in this chapter: a typed variable, string input, explicit type conversion from string to integer and back, and arithmetic on the result.
Integer, Real, Boolean, String and Char cover most caseslet name := value introduces a variable; name := value gives an existing variable a new value0b), octal (0o) or hexadecimal (0x), with _ between digitsChar is a single character, written #a or by code point, #65/ discards the fractional part; use Real values for fractional results7 + 5) or as methods (7.plus(5)); both are equivalent:typecheck on does the same at the REPL+; other conversions still use .to_string, .to_integer, .to_real, and related methods.to_integer or .to_real on a non-numeric string raises an exception?String, ?Integer) can hold nil; always check before using themconsole gives access to keyboard input via read_line1. Define variables for the three sides of a right triangle — call them a, b, and c — with values 3, 4, and 5. Verify that a * a + b * b = c * c by printing the result of the comparison.
2. The Integer method pick returns a random integer in [0, n). At the REPL, call 100.pick several times and observe the results. Then write an expression that produces a random integer between 1 and 10 inclusive.
3. Write a program that reads a temperature in Celsius from the console and prints the Fahrenheit equivalent. The formula is F = C * 9.0 / 5.0 + 32.0. Remember that read_line returns a String, so you will need to convert it before doing arithmetic.
4. What is the value of " Hello, Nex ".trim.to_lower.length? Work it out by hand first, then verify at the REPL by chaining the method calls. Note that methods can be chained: the result of one call becomes the receiver of the next.
5. At the REPL, type let x := 10 and then let x := 20. What is x now? Then put the same two lines in a file and run it with nex. What does the error message say, and how would you change the second line so that the program runs?