Source Code

The Ceylon language module containing the core definitions referred to by the language specification, along with some basic functionality of use to most programs:

This module defines an abstraction over the basic facilities of the Java or JavaScript virtual machine, containing only functionality that can be easily implemented on both platforms. Thus, certain functionality, for example, concurrency, for which there is no common virtual machine-agnostic model, is not covered by the language module.

The language module is an implicit dependency of every other Ceylon module, and may not be explicitly imported.

By: Gavin King, Tom Bentley, Tako Schotanus, Stephane Epardaud, Enrique Zamudio
License: http://www.apache.org/licenses/LICENSE-2.0.html
Packages
ceylon.language

The root package of the Ceylon language module, functioning as the core of the Ceylon platform, and covering the…

ceylon.language.meta

The Ceylon metamodel base package.

ceylon.language.meta.declaration

The Ceylon metamodel open type and declaration package.

ceylon.language.meta.model

The Ceylon metamodel closed type and model package.

ceylon.language.serialization

The Ceylon serialization infrastructure.

Dependencies
java.base (jvm)7

The root package of the Ceylon language module, functioning as the core of the Ceylon platform, and covering the following areas of functionality:

Finally, this module defines the most useful and interesting void function of all time ever.

Declarations belonging to this package need not be explicitly imported by other source files.

By: Gavin King, Tom Bentley, Tako Schotanus, Stephane Epardaud, Enrique Zamudio
Annotations
abstractSource Codeshared AbstractAnnotation abstract()

Annotation to mark a class as abstract. An abstract class may have formal members, but may not be directly instantiated. An enumerated class must be abstract.

actualSource Codeshared ActualAnnotation actual()

Annotation to mark a member of a type as refining a member of a supertype.

aliasedSource Codeshared AliasesAnnotation aliased(String[] aliases)

Annotation to specify a list of aliases that tools such as auto-completion and quick-fixes should consider, to help users find a declaration using its aliases.

Parameters:
  • aliases

    The aliases, in plain text.

Since 1.2.0
annotationSource Codeshared AnnotationAnnotation annotation()

Annotation to mark a class as an annotation class, or a top-level function as an annotation constructor.

See also Annotation
bySource Codeshared AuthorsAnnotation by(String[] authors)

Annotation to document the authors of an API.

Parameters:
  • authors

    The authors, in Markdown syntax, of the annotated program element

defaultSource Codeshared DefaultAnnotation default()

Annotation to mark a member whose implementation may be refined by subtypes. Non-default declarations may not be refined.

deprecatedSource Codeshared DeprecationAnnotation deprecated(String reason = "")

Annotation to mark program elements which should not be used anymore.

Parameters:
  • reason = ""

    A description, in Markdown syntax, of why the program element is deprecated, and what alternatives are available.

docSource Codeshared DocAnnotation doc(String description)

Annotation to specify API documentation of a program element. The doc annotation need not be explicitly specified, since a string literal at the beginning of a declaration is implicitly considered an argument to doc().

"Something awesome"
void hello() => print("hello");

Is an abbreviation for:

doc ("Something awesome")
void hello() => print("hello");
Parameters:
  • description

    Documentation, in Markdown syntax, describing the annotated program element

finalSource Codeshared FinalAnnotation final()

Annotation to mark a class as final. A final class may not be extended. Marking a class as final affects disjoint type analysis.

formalSource Codeshared FormalAnnotation formal()

Annotation to mark a member whose implementation must be provided by subtypes.

lateSource Codeshared LateAnnotation late()

Annotation to disable definite initialization analysis for a toplevel value, or for an attribute of a class.

  • In the case of a class attribute, the attribute may not be initialized by its declaration, and may be left unassigned by the class initializer.
  • In the case of a toplevel value, the value may not be initialized by its declaration.

A late value may be assigned by any code to which it is visible, but repeated assignment produces an InitializationError.

Evaluation of a late value cannot be guaranteed sound by the compiler, and so evaluation of a late value before initialization produces an InitializationError.

licenseSource Codeshared LicenseAnnotation license(String description)

Annotation to specify the URL of the license of a module or package.

Parameters:
  • description

    The name, text, or URL of the license.

nativeSource Codeshared NativeAnnotation native(String[] backends)

Annotation to mark a module, import, or declaration as platform-native.

For example, this code defines a native function in a cross-platform module:

import java.lang { System }

native void hello();

native ("jvm") void hello() {
    System.out.println("hello");
}

native ("js") void hello() {
    dynamic {
        console.log("hello");
    }
}
optionalSource Codeshared OptionalImportAnnotation optional()

Annotation to specify that a module can be executed even if the annotated dependency is not available.

optional import org.some.service.provider "1.2.3";
sealedSource Codeshared SealedAnnotation sealed()

Annotation to mark an interface, class, or constructor as sealed. A sealed interface may not be satisfied outside of the module in which it is defined. A sealed class may not be extended or instantiated outside of the module in which it is defined. A sealed constructor may not be invoked outside of the module in which it is defined.

Since 1.1.0
seeSource Codeshared SeeAnnotation see(Declaration[] programElements)

Annotation to specify references to other program elements related to the annotated API.

Parameters:
  • programElements

    The program elements being referred to.

serializableSource Codeshared SerializableAnnotation serializable()

Annotation to specify that a class is serializable.

A serializable class may have instances that cannot be serialized if those instances have reachable references to instances of non-serializable classes.

Since 1.2.0
serviceSource Codeshared ServiceAnnotation service(ClassOrInterfaceDeclaration contract)

Annotation marking a class as implementing a service. The class must be a non-abstract, shared, toplevel class.

For example, if Manager is an interface, this code declares an implementation of Manager:

service (`Manager`)
shared class DefautManager() satisfies Manager {}

Service implementations can be found at runtime using Module.findServiceProviders().

{Manager*} managers = `module`.findServiceProviders(`Manager`);
assert (exists manager = managers.first);
Parameters:
  • contract

    The service interface or class that the annotated class provides.

Since 1.3.0
sharedSource Codeshared SharedAnnotation shared()

Annotation to mark a declaration as shared. A shared declaration is visible outside the block of code in which it is declared.

sinceSource Codeshared SinceAnnotation since(String version)

Annotation to indicate at which moment the annotated declaration was added to the module.

Parameters:
  • version

    The version of the module when this declaration was added.

Since 1.3.0
smallSource Codeshared SmallAnnotation small()

Annotation to hint to the compiler that, if possible:

  • an Integer type should be represented using a 32-bit signed integer,
  • a Float type should be represented using 32-bit IEEE float, or
  • a Character type should be represented as a single 16-bit code point in the Basic Multilingual Plane.

The compiler is permitted to ignore this hint.

small Integer zero = 0;
Since 1.3.0
staticSource Codeshared StaticAnnotation static()

Annotation to mark a member of a toplevel class as static. A static member does not have access to any current instance of the class, and must occur before all constructor declarations and non-static member declarations in the body of the class.

For example:

class Hello {
    shared static void hello() => print("hello");
    shared new() {}
}

A static member may be invoked or evaluated without any receiving instance of the class, by qualifying the member by a reference to the class itself.

shared void run() => Hello.hello();

The type parameters of a generic class are in scope at the declaration of a static member.

class Box<Element> {
    shared static Box<Element>[2] pair(Element x, Element y)
           => [create(x), create(y)];
    shared new create(Element element) {}
}

Box<Float>[2] boxes = Box.pair(1.0, 2.0);
suppressWarningsSource Codeshared SuppressWarningsAnnotation suppressWarnings(String[] warnings)

Annotation to suppress compilation warnings of the specified types when typechecking the annotated program element.

Parameters:
  • warnings

    The warning types to suppress.

    Allowed warning types are: filenameNonAscii, filenameCaselessCollision, deprecation, disjointEquals, disjointContainment, compilerAnnotation, doclink, expressionTypeNothing, expressionTypeCallable, expressionTypeIterable, unusedDeclaration, unusedImport, redundantImportAlias, ceylonNamespace, javaNamespace, suppressedAlready, suppressesNothing, unknownWarning, ambiguousAnnotation, javaAnnotationElement, syntaxDeprecation, smallIgnored, literalNotSmall, disjointEquals, disjointContainment, redundantNarrowing, redundantIteration, missingImportPrefix, uncheckedTypeArguments, inferredNotNull.

Since 1.2.0
taggedSource Codeshared TagsAnnotation tagged(String[] tags)

Annotation to categorize an API by tag.

Parameters:
  • tags

    The tags, in plain text.

throwsSource Codeshared ThrownExceptionAnnotation throws(Declaration type, String when = "")

Annotation to document the exception types thrown by a function, value, class, or constructor.

throws(`class Exception`)
void die() { throw; }
Parameters:
  • type

    The Exception type that is thrown.

  • when = ""

    A description, in Markdown syntax, of the circumstances that cause this exception to be thrown.

variableSource Codeshared VariableAnnotation variable()

Annotation to mark a value as variable. A variable value may be assigned multiple times.

AbstractAnnotationSource Codeshared final AbstractAnnotation

The annotation class for the abstract() annotation.

ActualAnnotationSource Codeshared final ActualAnnotation

The annotation class for the actual() annotation.

AliasesAnnotationSource Codeshared final AliasesAnnotation

The annotation class for the aliased() annotation.

AnnotationAnnotationSource Codeshared final AnnotationAnnotation

The annotation class for the annotation() meta-annotation.

AuthorsAnnotationSource Codeshared final AuthorsAnnotation

The annotation class for the by() annotation.

DefaultAnnotationSource Codeshared final DefaultAnnotation

The annotation class for the default() annotation.

DeprecationAnnotationSource Codeshared final DeprecationAnnotation

The annotation class for the deprecated() annotation.

DocAnnotationSource Codeshared final DocAnnotation

The annotation class for the doc() annotation.

FinalAnnotationSource Codeshared final FinalAnnotation

The annotation class for the final() annotation.

FormalAnnotationSource Codeshared final FormalAnnotation

The annotation class for the formal() annotation.

LateAnnotationSource Codeshared final LateAnnotation

The annotation class for the late() annotation.

LicenseAnnotationSource Codeshared final LicenseAnnotation

The annotation class for the license() annotation.

NativeAnnotationSource Codeshared final NativeAnnotation

The annotation class for the native() annotation.

OptionalImportAnnotationSource Codeshared final OptionalImportAnnotation

The annotation class for the optional() annotation.

SealedAnnotationSource Codeshared final SealedAnnotation

The annotation class for the sealed() annotation.

SeeAnnotationSource Codeshared final SeeAnnotation

The annotation class for the see() annotation.

SerializableAnnotationSource Codeshared final SerializableAnnotation

The annotation class for the serializable() annotation.

ServiceAnnotationSource Codeshared final ServiceAnnotation

The annotation class for the service() annotation.

SharedAnnotationSource Codeshared final SharedAnnotation

The annotation class for the shared() annotation.

SinceAnnotationSource Codeshared final SinceAnnotation

The annotation class for the since() annotation.

SmallAnnotationSource Codeshared final SmallAnnotation

The annotation class for the small() annotation.

StaticAnnotationSource Codeshared final StaticAnnotation

The annotation class for the static() annotation.

SuppressWarningsAnnotationSource Codeshared final SuppressWarningsAnnotation

The annotation class for the suppressWarnings() annotation.

TagsAnnotationSource Codeshared final TagsAnnotation

The annotation class for the tagged() annotation.

ThrownExceptionAnnotationSource Codeshared final ThrownExceptionAnnotation

The annotation class for the throws() annotation.

VariableAnnotationSource Codeshared final VariableAnnotation

The annotation class for the variable() annotation.

Values
emptySource Codeshared empty empty

A sequence with no elements, abbreviated []. The unique instance of the type [].

By: Tako Schotanus
emptyIteratorSource Codeshared emptyIterator emptyIterator

An iterator that returns no elements.

emptyMapSource Codeshared emptyMap emptyMap

An immutable Map with no entries.

emptySetSource Codeshared emptySet emptySet

An immutable Set with no elements.

equalSource Codeshared equal equal

The value is exactly equal to the given value.

falseSource Codeshared false false

A value representing falsity in Boolean logic.

finishedSource Codeshared finished finished

A value that indicates that an Iterator is exhausted and has no more values to return.

See also Iterator
infinitySource Codeshared Float infinity

An instance of Float representing positive infinity, ∞, the result of dividing a positive number by zero. Negative infinity, -∞, the result of dividing a negative number by zero, is the additive inverse -infinity.

Note that any floating-point computation that results in a positive value too large to be represented as a Float is “rounded up” to infinity. Likewise, any floating-point computation that yields a negative value whose magnitude is too large to be represented as a Float is “rounded down” to -infinity.

languageSource Codeshared language language

Contains information about the Ceylon language version.

largerSource Codeshared larger larger

The value is larger than the given value.

nothingSource Codeshared Nothing nothing

A value getter of type Nothing. The expression nothing is formally assignable to any type, but produces an exception when evaluated.

(This is most useful for tool-generated implementations of formal members.)

Throws
nullSource Codeshared null null

The null value.

By: Gavin
operatingSystemSource Codeshared operatingSystem operatingSystem

Represents the operating system on which the current process is running.

processSource Codeshared process process

Represents the current process (instance of the virtual machine).

By: Gavin, Tako
runtimeSource Codeshared runtime runtime

Represents the machine and virtual machine on which the current process is executing.

Holds information about runtime name, version and about inherent limitations like minimum/maximum values that can be represented by the runtime.

smallerSource Codeshared smaller smaller

The value is smaller than the given value.

systemSource Codeshared system system

Represents the system on which the current process is executing.

Holds information about system time and locale.

trueSource Codeshared true true

A value representing truth in Boolean logic.

Functions
andSource Codeshared Boolean and<in Value>(Boolean(Value) p, Boolean(Value) q)(Value val)

Returns a function which is the logical conjunction of the given predicate functions.

Parameters:
  • p

    The first predicate function

  • q

    The second predicate function

Since 1.1.0
anySource Codeshared Boolean any({Boolean*} values)

Determines if any one of the given boolean values (usually a comprehension) is true.

Boolean anyNegative = any { for (x in xs) x<0.0 };

If there are no boolean values, return false.

anyPairSource Codeshared Boolean anyPair<First, Second>(Boolean selecting(First first, Second second), {First*} firstIterable, {Second*} secondIterable)

Given two streams, return true if some pair of elements in the given streams satisfies the given binary predicate function, or false otherwise. If one of the streams is longer than the other, simply ignore additional elements of the longer stream with no pair in the other stream. If either stream is empty, return false.

For any given streams xs and ys, and predicate function p, anyPair() may be defined in terms of Iterable.any(), zipPairs(), and unflatten():

anyPair(p, xs, ys) == zipPairs(xs, ys).any(unflatten(p))
Parameters:
  • selecting

    The binary predicate function to apply to each pair of elements.

See also everyPair()
Since 1.1.0
applySource Codeshared Return apply<Return, Args>(Return(*Args) f, Args args)

Applies an arbitrary Return(*Arguments)

to the given arguments. The arguments must be packaged into a Tuple whose type is compatible with the Callable type.

For example, given the following argument tuple:

 [Boolean(Character), Boolean, Boolean] tuple
     = [Character.whitespace, true, false];

We can apply String.split() to the arguments given in tuple as follows:

String string = ... ;
{String*} strings = apply(string.split, tuple);

Application may be abbreviated using the spread operator:

String string = ... ;
{String*} strings = string.split(*tuple)

In practice, this behaves as if the Callable were called with the elements of the tuple as its arguments. The examples above are both equivalent to:

string.split(Character.whitespace, true, false)
See also unflatten()
arrayOfSizeSource Codeshared Array<Element> arrayOfSize<Element>(Integer size, Element element)

Deprecated: Use Array.ofSize()

Create an array of the specified size, populating every index with the given element. The specified size must be no larger than runtime.maxArraySize. If size<=0, the new array will have no elements.

Parameters:
  • size

    The size of the resulting array. If the size is non-positive, an empty array will be created.

  • element

    The element value with which to populate the array. All elements of the resulting array will have the same value.

Throws
byDecreasingSource Codeshared Comparison byDecreasing<Element, Value>(Value comparable(Element e))(Element x, Element y)
given Value satisfies Comparable<Value>

Produces a comparator function which orders elements in decreasing order according to the Comparable value returned by the given comparable() function.

 "Hello World!".sort(byDecreasing(Character.lowercased))

This function is intended for use with Iterable.sort() and Iterable.max().

byIncreasingSource Codeshared Comparison byIncreasing<Element, Value>(Value comparable(Element e))(Element x, Element y)
given Value satisfies Comparable<Value>

Produces a comparator function which orders elements in increasing order according to the Comparable value returned by the given comparable() function.

 "Hello World!".sort(byIncreasing(Character.lowercased))

This function is intended for use with Iterable.sort() and Iterable.max().

byItemSource Codeshared Comparison byItem<Item>(Comparison comparing(Item x, Item y))(Object->Item x, Object->Item y)
given Item satisfies Object

A comparator for Entrys which compares their items according to the given comparing() function.

value sortedEntries = map.sort(byItem(byIncreasing(String.lowercased)));

This function is intended for use with Iterable.sort() and Iterable.max().

See also byKey()
byKeySource Codeshared Comparison byKey<Key>(Comparison comparing(Key x, Key y))(Key->Object x, Key->Object y)
given Key satisfies Object

A comparator for Entrys which compares their keys according to the given comparing() function.

value sortedEntries = map.sort(byKey(byIncreasing(String.lowercased)));

This function is intended for use with Iterable.sort() and Iterable.max().

See also byItem()
classNameSource Codeshared String className(Anything obj)

Return the name of the concrete class of the given object, in a format native to the virtual machine. For example, className(0) evaluates to:

  • "ceylon.language.Integer" on the Java Virtual Machine, and to
  • "ceylon.language::Integer" on a JavaScript VM.

To obtain a platform-independent class name, use the type() function to obtain a metamodel object, for example:

type(1).declaration.qualifiedName

evaluates to "ceylon.language::Integer" on every platform.

See also type()
compareCorrespondingSource Codeshared Comparison compareCorresponding<First, Second>({First*} firstIterable, {Second*} secondIterable, Comparison comparing(First first, Second second))

Compares corresponding elements of the given streams using the given comparison function. Two elements are considered corresponding if they occupy the same position in their respective streams. Returns:

  • the result of the given comparison for the earliest pair of corresponding elements whose comparison does not evaluate to equal, or, otherwise, if every comparison of corresponding pairs of elements produces equal,
  • smaller, if the first stream produces fewer elements than the second stream,
  • larger, if the first stream produces more elements than the second stream, or
  • equal if the two streams produce the same number of elements.

If both streams are empty, return equal.

For example:

compareCorresponding({ 1, 2, 2, 5 }, 1:4,
       (Integer i, Integer j) => i<=>j)

and:

compareCorresponding({ 1, 2, 3 }, 1:4,
       (Integer i, Integer j) => i<=>j)

both evaluate to smaller.

Parameters:
  • comparing

    The comparison function that compares an element of the first stream with the corresponding element of the second stream.

Since 1.3.0
comparingSource Codeshared Comparison comparing<in Value>(Comparison(Value, Value)[] comparators)(Value x, Value y)

A single comparator function which delegates to each of the given comparator functions in turn, returning the first result of smaller or larger if any, or returning equal otherwise.

Consider the following type:

class Person(shared Integer age, shared String name) {}

A stream of Persons may be sorted by age, breaking ties by name, like this:

people.sort(comparing(byDecreasing(Person.age), byIncreasing(Person.name)))

If no comparators are given, the resulting comparator always returns equal.

This function is intended for use with Iterable.sort() and Iterable.max().

Since 1.1.0
composeSource Codeshared X(*Args) compose<X, Y, Args>(X(Y) x, Y(*Args) y)

Given a function with return type Y, and a second function with a single parameter also of type Y, return the composition of the two functions. The first function may have any number of parameters.

For any such functions f() and g(),

compose(g,f)(*args)==g(f(*args))

for every possible argument tuple args of f().

See also curry(), uncurry()
concatenateSource Codeshared Element[] concatenate<Element>({Element*}[] iterables)

Given zero or more argument streams, return a new sequence containing all elements of every given stream. The elements of the resulting stream are ordered first according to the stream in which they occur, and then according to where they occur in that stream. If there are no arguments, or if none of the argument streams contain any elements, return the empty sequence.

For example, the expression

concatenate(1..3, [0.0], {"hello", "world"})

results in the sequence [1, 2, 3, 0.0, "hello", "world"] which has the type [Integer|Float|String*].

Parameters:
  • iterables

    The streams to concatenate.

correspondingSource Codeshared Boolean corresponding<First, Second>({First*} firstIterable, {Second*} secondIterable, Boolean comparing(First first, Second second) = ...)

Compares corresponding elements of the given streams using the given binary predicate function. Two elements are considered corresponding if they occupy the same position in their respective streams. Returns true if and only if:

  • the two streams have the same number of elements, and
  • if the predicate is satisfied for every pair of corresponding elements.

Returns false otherwise. If both streams are empty, return true.

For example:

corresponding({ 1, 2, 3, 4 }, 1:4)

and:

corresponding({ 1, 2, 3, 4 }, "1234", 
       (Integer i, Character c) => i.string==c.string)

both evaluate to true.

Parameters:
  • comparing = if (exists first, exists second) then first==second else !first exists && !second exists

    The predicate function that compares an element of the first stream with the corresponding element of the second stream.

    By default, the elements are compared by a predicate function that returns true if and only if the elements are equal or both null.

Since 1.1.0
countSource Codeshared Integer count({Boolean*} values)

A count of the number of true items in the given values.

Integer negatives = count { for (x in xs) x<0.0 };
currySource Codeshared Return(*Rest) curry<Return, Argument, First, Rest>(Return(*Tuple<Argument,First,Rest>) f)(First first)
given First satisfies Argument

Curries a function, returning a function with two parameter lists, given a function with at least one parameter. The first parameter list of the returned function has just the first parameter of the original function, and the second parameter list has the remaining parameters.

That is, if fun has type W(X,Y,Z) then curry(fun) has type W(Y,Z)(X).

decreasingSource Codeshared Comparison decreasing<Element>(Element x, Element y)
given Element satisfies Comparable<Element>

A comparator function which orders elements in decreasing natural order.

   "Hello World!".sort(decreasing)

This function is intended for use with Iterable.sort() and Iterable.max().

Since 1.2.0
decreasingItemSource Codeshared Comparison decreasingItem<Item>(Object->Item x, Object->Item y)
given Item satisfies Comparable<Item>

A comparator function which orders entries by decreasing natural order of their items.

This function is intended for use with Iterable.sort() and Iterable.max().

Since 1.2.0
decreasingKeySource Codeshared Comparison decreasingKey<Key>(Key->Anything x, Key->Anything y)
given Key satisfies Comparable<Key>

A comparator function which orders entries by decreasing natural order of their keys.

This function is intended for use with Iterable.sort() and Iterable.max().

Since 1.2.0
emptyOrSingletonSource Codeshared []|[Element&Object] emptyOrSingleton<Element>(Element element)

A singleton Tuple with the given element if the given element is non-null, or the empty sequence otherwise. This operation transforms an optional type T? to a sequence type []|[T] allowing optional values to be the subject of operations defined for streams.

For example, flat mapping emptyOrSingleton() reproduces the behavior of Iterable.coalesced. The expression

{ "1.23", "foo", "5.67", "-1", "" }
        .map(parseFloat)
        .flatMap(emptyOrSingleton<Float?>)

produces the stream:

{ 1.23, 5.67, -1.0 }
See also Tuple, Empty
everySource Codeshared Boolean every({Boolean*} values)

Determines if every one of the given boolean values (usually a comprehension) is true.

Boolean allPositive = every { for (x in xs) x>0.0 };

If there are no boolean values, return true.

everyPairSource Codeshared Boolean everyPair<First, Second>(Boolean selecting(First first, Second second), {First*} firstIterable, {Second*} secondIterable)

Given two streams, return true if every pair of elements in the given streams satisfies the given binary predicate function, or false otherwise. If one of the streams is longer than the other, simply ignore additional elements of the longer stream with no pair in the other stream. If either stream is empty, return true.

For any given streams xs and ys, and predicate function p, everyPair() may be defined in terms of Iterable.every(), zipPairs(), and unflatten():

everyPair(p, xs, ys) == zipPairs(xs, ys).every(unflatten(p))
Parameters:
  • selecting

    The binary predicate function to apply to each pair of elements.

Since 1.1.0
expandSource Codeshared Iterable<Element,OuterAbsent|InnerAbsent> expand<Element, OuterAbsent, InnerAbsent>(Iterable<Iterable<Element,InnerAbsent>,OuterAbsent> iterables)
given OuterAbsent satisfies Null
given InnerAbsent satisfies Null

Given a stream whose elements are also streams, return a new stream with all elements of every nested stream. If there are no nested streams, or if all of the nested streams are empty, return an empty stream.

For example, the expression

expand { 1..3, {5}, "hi" }

results in the stream { 1, 2, 3, 5, 'h', 'i' } which has the type {Integer|Character*}.

Since 1.1.0
findPairSource Codeshared [First, Second]? findPair<First, Second>(Boolean selecting(First first, Second second), {First*} firstIterable, {Second*} secondIterable)

Given two streams, return the first pair of elements in the given streams that satisfies the given binary predicate function, or null if no pair of elements satisfies the predicate. If one of the streams is longer than the other, simply ignore additional elements of the longer stream with no pair in the other stream.

For any given streams xs and ys, and predicate function p, findPair() may be defined in terms of Iterable.find(), zipPairs(), and unflatten():

findPair(p, xs, ys) == zipPairs(xs, ys).find(unflatten(p))
Parameters:
  • selecting

    The binary predicate function to apply to each pair of elements.

Since 1.1.0
flattenSource Codeshared Return(*Args) flatten<Return, Args>(Return tupleFunction(Args tuple))

Given a function with a single parameter of tuple type [P1, P2, ..., Pn], return a function with multiple parameters of type P1, P2, …, Pn.

That is, if fun has type W([X,Y,Z]) then flatten(fun) has type W(X,Y,Z).

In the case of a function whose parameter type is a sequence type or unterminated tuple type, the returned function is variadic:

  • if the given function accepts [S*], the returned function has a single variadic parameter of type S*,
  • if the given function accepts [S+], the returned function has a single variadic parameter of type S+,
  • if the given function accepts [P1, P2, ..., Pn, S*], the returned function has multiple parameters with types P1, P2, …, Pn, S*, or
  • if the given function accepts [P1, P2, ..., Pn, S+], the returned function has multiple parameters with types P1, P2, …, Pn, S+.
See also unflatten()
foldPairsSource Codeshared Result foldPairs<Result, First, Second>(Result initial, Result accumulating(Result partial, First first, Second second), {First*} firstIterable, {Second*} secondIterable)

Given two streams, return the result of applying the given accumulating function to each pair of elements of the given streams in turn. If one of the streams is longer than the other, simply ignore additional elements of the longer stream with no pair in the other stream.

For any given streams xs and ys, initial value z, and combining function f, foldPairs() may be defined in terms of Iterable.fold(), zipPairs(), and unflatten():

foldPairs(z, f, xs, ys) == zipPairs(xs, ys).fold(z)(unflatten(f))
Parameters:
  • accumulating

    The accumulating function to apply to each pair of elements.

Since 1.1.0
forItemSource Codeshared Result forItem<Item, Result>(Result resulting(Item item))(Object->Item entry)

A function that returns the result of applying the given function to the item of a given Entry, discarding its key.

Map<String,List<Item>> map = ... ;
{Item?*} topItems = map.map(forItem(List<Item>.first));
See also forKey()
forKeySource Codeshared Result forKey<Key, Result>(Result resulting(Key key))(Key->Anything entry)
given Key satisfies Object

A function that returns the result of applying the given function to the key of a given Entry, discarding its item.

Map<String,List<Item>> map = ... ;
{String*} uppercaseKeys = map.map(forKey(String.uppercased));
See also forItem()
formatFloatSource Codeshared String formatFloat(Float float, Integer minDecimalPlaces = 1, Integer maxDecimalPlaces = ..., Character decimalSeparator = ..., Character? thousandsSeparator = null)

Deprecated: Use Float.format()

The string decimal representation of the given floating point number. If the given number is negative, the string representation will begin with -. The whole part and fractional parts of the number are separated by a . decimal point. Digits consist of decimal digits 0 to 9.

The number of decimal places following the decimal point is controlled by the parameters minDecimalPlaces and maxDecimalPlaces, which default to 1 and 9 respectively, so that by default the string representation always contains a decimal point, and never contains more than nine decimal places. The decimal representation is rounded so that the number of decimal places never exceeds the specified maximum.

For example:

  • formatFloat(1234.1234) is "1234.1234"
  • formatFloat(0.1234) is "0.1234"
  • formatFloat(1234.0) is "1234.0"
  • formatFloat(1234.0,0) is "1234"
  • formatFloat(1234.1234,6) is "1234.123400"
  • formatFloat(1234.1234,0,2) is "1234.12"
  • formatFloat(1234.123456,0,5) is "1234.12346"
  • formatFloat(0.0001,2,2) is "0.00"
  • formatFloat(0.0001,0,2) is "0"

Finally:

  • formatFloat(-0.0) is "0.0",
  • formatFloat(0.0/0) is "NaN",
  • formatFloat(1.0/0) is "Infinity", and
  • formatFloat(-1.0/0) is "-Infinity".

This function never produces a representation involving scientific notation.

Parameters:
  • float

    The floating point value to format.

  • minDecimalPlaces = 1

    The minimum number of allowed decimal places.

    If minDecimalPlaces<=0, the result may have no decimal point.

  • maxDecimalPlaces = 9

    The maximum number of allowed decimal places.

    If maxDecimalPlaces<=0, the result always has no decimal point.

  • decimalSeparator = '.'

    The character to use as the decimal separator.

    decimalSeparator may not be '-' or a digit as defined by the Unicode general category Nd.

  • thousandsSeparator = null

    If not null, thousandsSeparator will be used to separate each group of three digits, starting immediately to the left of the decimal separator.

    thousandsSeparator may not be equal to the decimalSeparator and may not be '-' or a digit as defined by the Unicode general category Nd.

Since 1.2.0
formatIntegerSource Codeshared String formatInteger(Integer integer, Integer radix = ..., Character? groupingSeparator = null)

Deprecated: Use Integer.format()

The string representation of the given integer in the base given by radix. If the given integer is negative, the string representation will begin with -. Digits consist of decimal digits 0 to 9, together with and lowercase letters a to z for bases greater than 10.

For example:

  • formatInteger(-46) is "-46"
  • formatInteger(9,2) is "1001"
  • formatInteger(10,8) is "12"
  • formatInteger(511,16) is "1ff"
  • formatInteger(512,32) is "g0"
Parameters:
  • integer

    The integer value to format.

  • radix = 10

    The base, between minRadix and maxRadix inclusive.

    • minRadix <= radix <= maxRadix
  • groupingSeparator = null

    If not null, groupingSeparator will be used to separate each group of three digits if radix is 10, or each group of four digits if radix is 2 or 16.

    groupingSeparator may not be '-', a digit as defined by the Unicode general category Nd, or a letter as defined by the Unicode general categories Lu, Ll, Lt, Lm, and Lo.

Throws
identicalSource Codeshared Boolean identical(Identifiable x, Identifiable y)

Determine if the arguments are identical(). Equivalent to x===y. Only instances of Identifiable have well-defined identity.

Parameters:
  • x

    An object with well-defined identity.

  • y

    A second object with well-defined identity.

identitySource Codeshared Value identity<Value>(Value argument)

The identity function that always returns its argument.

Since 1.1.0
identityHashSource Codeshared Integer identityHash(Identifiable identifiable)

Return the system-defined identity hash value of the given value. This hash value is consistent with identity equality.

See also identical()
increasingSource Codeshared Comparison increasing<Element>(Element x, Element y)
given Element satisfies Comparable<Element>

A comparator function which orders elements in increasing natural order.

   "Hello World!".sort(increasing)

This function is intended for use with Iterable.sort() and Iterable.max().

Since 1.2.0
increasingItemSource Codeshared Comparison increasingItem<Item>(Object->Item x, Object->Item y)
given Item satisfies Comparable<Item>

A comparator function which orders entries by increasing natural order of their items.

This function is intended for use with Iterable.sort() and Iterable.max().

Since 1.2.0
increasingKeySource Codeshared Comparison increasingKey<Key>(Key->Anything x, Key->Anything y)
given Key satisfies Comparable<Key>

A comparator function which orders entries by increasing natural order of their keys.

This function is intended for use with Iterable.sort() and Iterable.max().

Since 1.2.0
interleaveSource Codeshared Iterable<Element,Absent> interleave<Element, Absent>([Iterable<Element,Absent>+] iterables)
given Absent satisfies Null

Given one or more argument streams, return a stream containing elements of the given streams. The elements are ordered first according to their position in the argument stream, and then according to the stream in which they occur. The resulting stream contains exactly the same number of elements from each stream.

For example, the expression

interleave(1..5, "-+".cycled)

results in the stream { 1, '-', 2, '+', 3, '-', 4, '+', 5, '-' }.

Since 1.1.0
iterateSee loop()
largestSource Codeshared Element largest<Element>(Element x, Element y)
given Element satisfies Comparable<Element>

Given two Comparable values, return largest of the two.

If exactly one of the given values violates the reflexivity requirement of Object.equals() such that x!=x, then the other value is returned. In particular, if exactly one is an undefined Float (Float.undefined), it is not returned.

loopSource Codeshared {Element+} loop<Element>(Element first)(Element|Finished next(Element element))

Produces the stream that results from repeated application of the given function to the given first element of the stream, until the function first returns finished. If the given function never returns finished, the resulting stream is infinite.

For example:

loop(0)(2.plus).takeWhile(10.largerThan)

produces the stream { 0, 2, 4, 6, 8 }.

Parameters:
  • first

    The first element of the resulting stream.

  • next

    The function that produces the next element of the stream, given the current element. The function may return finished to indicate the end of the stream.

Since 1.1.0
Aliases: iterate
mapSource Codeshared Map<Key,Item> map<Key, Item>({<Key->Item>*} stream, Item choosing(Item earlier, Item later) = ...)
given Key satisfies Object

Create a new immutable Map containing every Entry produced by the given stream, resolving items with duplicate keys according to the given function.

For example:

map { 1->"hello", 2->"goodbye" }

produces the map { 1->"hello", 2->"goodbye" }.

This is an eager operation and the resulting map does not reflect changes to the given stream.

Parameters:
  • stream

    The stream of entries.

  • choosing = earlier

    A function that chooses between items with duplicate keys. By default, the item that occurs earlier in the stream is chosen.

Since 1.2.0
mapPairsSource Codeshared Iterable<Result,FirstAbsent|SecondAbsent> mapPairs<Result, First, Second, FirstAbsent, SecondAbsent>(Result collecting(First first, Second second), Iterable<First,FirstAbsent> firstIterable, Iterable<Second,SecondAbsent> secondIterable)
given FirstAbsent satisfies Null
given SecondAbsent satisfies Null

Given two streams, form a new stream by applying a binary mapping function to pairs of elements in the given streams. If one of the streams is longer than the other, simply ignore additional elements of the longer stream with no pair in the other stream. The length of the resulting stream is the length of the shorter of the two given streams.

For any given streams xs and ys, and mapping function f, mapPairs() may be defined in terms of Iterable.map(), zipPairs(), and unflatten():

mapPairs(f, xs, ys) == zipPairs(xs, ys).map(unflatten(f))

For example the expression

mapPairs((Float x, Float y) => (x^2+y^2)^0.5, 
        {3.0, 5.0, 6.0, 9.0}, {4.0, 12.0, 8.0, 12.0})

evaluates to the stream { 5.0, 13.0, 10.0, 15.0 }.

Parameters:
  • collecting

    The mapping function to apply to the pair of elements.

maxSource Codeshared Absent|Value max<Value, Absent>(Iterable<Value,Absent> values)
given Value satisfies Comparable<Value>
given Absent satisfies Null

Given a stream of Comparable values, return the largest value in the stream, or null if the stream is empty.

For any nonempty stream it, max(it) evaluates to the first element of it such that for every element e of it, max(it) >= e.

Any value x which violates the reflexivity requirement of Object.equals() such that x!=x is skipped, unless it is the last element in the stream. Thus, for a stream of Floats, max() will not return an undefined value unless every element of the stream is undefined.

Note that Iterable.max() may be used to find the largest value in any stream, as determined by a given comparator function.

measureSource Codeshared Range<Element>|[] measure<Element>(Element first, Integer size)
given Element satisfies Enumerable<Element>

Produces a Range of adjacent Enumerable values generated by a first element, and a strictly positive size, or returns the empty sequence if size <= 0. The range includes all values whose offset from first is non-negative and less than the size.

More precisely, if x and first are of Enumerable type X, and size is an integer, then x in first:size if and only if 0 <= x.offset(first) < size.

The measure operator : is an abbreviation for measure():

for (i in start:size) { ... }
for (char in '0':10) { ... }

The measure operator accepts the first index and size of the range:

0:5     // [0, 1, 2, 3, 4]

If the size is nonpositive, the range is empty:

0:0     // []
5:0     // []
0:-5    // []
Since 1.1.0
minSource Codeshared Absent|Value min<Value, Absent>(Iterable<Value,Absent> values)
given Value satisfies Comparable<Value>
given Absent satisfies Null

Given a stream of Comparable values, return the smallest value in the stream, or null if the stream is empty.

For any nonempty stream it, min(it) evaluates to the first element of it such that for every element e of it, min(it) <= e.

Any value x which violates the reflexivity requirement of Object.equals() such that x!=x is skipped, unless it is the last element in the stream. Thus, for a stream of Floats, min() will not return an undefined value unless every element of the stream is undefined.

noopSource Codeshared void noop(Anything[] arguments)

A void function that does nothing.

Since 1.1.0
notSource Codeshared Boolean not<in Value>(Boolean(Value) p)(Value val)

Returns a function which is the logical negation of the given predicate function.

Parameters:
  • p

    The predicate function to negate

Since 1.1.0
orSource Codeshared Boolean or<in Value>(Boolean(Value) p, Boolean(Value) q)(Value val)

Returns a function which is the logical disjunction of the given predicate functions.

Parameters:
  • p

    The first predicate function

  • q

    The second predicate function

Since 1.1.0
parseBooleanSource Codeshared Boolean? parseBoolean(String string)

Deprecated: Use Boolean.parse()

The Boolean value of the given string representation of a boolean value, or null if the string does not represent a boolean value.

Recognized values are "true", "false".

parseFloatSource Codeshared Float? parseFloat(String string)

Deprecated: Use Float.parse()

The Float value of the given string representation of a decimal floating point number, or null if the string does not represent a decimal floating point number.

If the given string representation contains more digits than can be represented by a Float, then the least significant digits are ignored.

The syntax accepted by this method is the same as the syntax for a Float literal in the Ceylon language except that it may optionally begin with a sign character (+ or -) and may not contain grouping underscore characters. That is, an optional sign character, followed by a string of decimal digits, followed by an optional decimal point and string of decimal digits, followed by an optional decimal exponent, for example e+10 or E-5, or SI magnitude, k, M, G, T, P, m, u, n, p, or f.

Float: Sign? Digits ('.' Digits)? (Magnitude|Exponent)
Sign: '+' | '-'
Magnitude: 'k' | 'M' | 'G' | 'T' | 'P' | 'm' | 'u' | 'n' | 'p' | 'f'
Exponent: ('e'|'E') Sign? Digits
Digits: ('0'..'9')+
See also Float.parse()
parseIntegerSource Codeshared Integer? parseInteger(String string, Integer radix = ...)

Deprecated: Use Integer.parse()

The Integer value of the given string representation of an integer value in the base given by radix, or null if the string does not represent an integer in that base, or if the mathematical integer it represents is too large in magnitude to be represented by an instance of the class Integer.

The syntax accepted by this function depends upon the given base:

  • For base 10, the accepted syntax is the same as the syntax for an Integer literal in the Ceylon language except that it may optionally begin with a sign character (+ or -) and may not contain grouping underscore characters. That is, an optional sign character, followed be a string of decimal digits, followed by an optional SI magnitude: k, M, G, T, or P.
  • For other bases, the accepted syntax is an optional sign character, followed by a string of digits of the given base.

The given radix specifies the base of the string representation. The list of available digits starts from 0 to 9, followed by a to z. When parsing in a specific base, the first radix digits from the available digits list is used. This function is not case sensitive; a and A both correspond to the digit a whose decimal value is 10.

Integer: Base10 | BaseN
Base10: Sign? Base10Digits Magnitude
BaseN: Sign? BaseNDigits
Sign: '+' | '-'
Magnitude: 'k' | 'M' | 'G' | 'T' | 'P'
Base10Digits: ('0'..'9')+
BaseNDigits: ('0'..'9'|'a'..'z'|'A'..'Z')+
Parameters:
  • string

    The string representation to parse.

  • radix = 10

    The base, between minRadix and maxRadix inclusive.

    • minRadix <= radix <= maxRadix
Throws
plusSource Codeshared Value plus<Value>(Value x, Value y)
given Value satisfies Summable<Value>

Add the given Summable values.

(1..100).by(2).fold(0)(plus<Integer>)
See also times(), sum()
printSource Codeshared void print(Anything val)

Print a line to the standard output of the virtual machine process, printing the given value's string, or <null> if the value is null.

This function is a shortcut for:

process.writeLine(line?.string else "<null>")

and is intended mainly for debugging purposes.

By: Gavin
printAllSource Codeshared void printAll({Anything*} values, String separator = ...)

Print multiple values to the standard output of the virtual machine process as a single line of text, separated by a given character sequence.

Parameters:
  • separator = ", "

    A character sequence to use to separate the values

By: Gavin
printStackTraceSource Codeshared void printStackTrace(Throwable exception, void write(String string) = ...)

Print the stack trace of the given Exception using the given function, or to standard error if no function is specified.

Parameters:
  • write = process.writeError(string)

    A function that prints the given string. Defaults to process.writeError().

productSource Codeshared Value product<Value>({Value+} values)
given Value satisfies Numeric<Value>

Given a nonempty stream of Numeric values, return the product of the values.

{Float+} values = ... ;
Float result = product(values);

For the case of a possibly-empty stream, form a nonempty stream starting with the unit element (the multiplicative identity).

{Float*} values = ... ;
Float result = product { 1.0, *values };
See also sum()
sequenceSource Codeshared [Element+]|Absent sequence<Element, Absent = Null>(Iterable<Element,Absent> elements)
given Absent satisfies Null

A nonempty sequence of the given elements, or null if the given stream is empty. A non-null, but possibly empty, sequence may be obtained using the else operator:

[Element*] sequenceOfElements = sequence(elements) else [];
By: Gavin
Since 1.1.0
setSource Codeshared Set<Element> set<Element>({Element*} stream, Element choosing(Element earlier, Element later) = ...)
given Element satisfies Object

Create a new immutable Set containing every element produced by the given stream, resolving items with duplicate keys according to the given function.

For example:

set { 0, 1, 1, 2, 3, 3, 3 }

produces the set { 0, 1, 2, 3 }.

This is an eager operation and the resulting set does not reflect changes to the given stream.

Parameters:
  • stream

    The stream of elements.

  • choosing = earlier

    A function that chooses between duplicate elements. By default, the element that occurs earlier in the stream is chosen.

Since 1.2.0
shuffleSource Codeshared Result(*FirstArgs)(*SecondArgs) shuffle<Result, FirstArgs, SecondArgs>(Result(*SecondArgs)(*FirstArgs) f)

Given a function with two parameter lists, return a function with the order of the argument lists reversed. The parameter lists may have any number of parameters.

That is, if fun has type W(A,B)(X,Y,Z) then shuffle(fun) has type W(X,Y,Z)(A,B).

This function is often used in conjunction with curry().

See also curry()
smallestSource Codeshared Element smallest<Element>(Element x, Element y)
given Element satisfies Comparable<Element>

Given two Comparable values, return smallest of the two.

If exactly one of the given values violates the reflexivity requirement of Object.equals() such that x!=x, then the other value is returned. In particular, if exactly one is an undefined Float (Float.undefined), it is not returned.

sortSource Codeshared Element[] sort<Element>({Element*} elements)
given Element satisfies Comparable<Element>

Sort the given elements according to their natural order, returning a new sequence.

Note that Iterable.sort() may be used to sort any stream according to a given comparator function.

spanSource Codeshared Range<Element> span<Element>(Element first, Element last)
given Element satisfies Enumerable<Element>

Produces a Range of adjacent Enumerable values generated by two endpoints: first and last. The range includes both endpoints, and all values falling between the endpoints.

  • For a recursive enumerable type, a value falls between the endpoints if its offset from first is less than the offset of last from first.
  • For a linear enumerable type, a value falls between the endpoints if the sign of its offset from first is the same as the sign of the offset of last from first and the sign of its offset from last is the opposite of the sign of the offset of last from first.

More precisely, if x, first, and last are of Enumerable type X, then x in first..last if and only if:

  • X is recursive and x.offset(first)<last.offset(first), or
  • X is linear and x.offsetSign(first)==last.offsetSign(first) and x.offsetSign(last)==-last.offsetSign(first).

For a linear enumerable type, a range is either increasing or decreasing:

  • in an increasing range, a value occurs before its successor and after its predecessor, but
  • in a decreasing range, a value occurs after its successor and before its predecessor.

The direction of the range depends upon the sign of the offset of last from first:

  • if last.offsetSign(first)>=0 the range is increasing, but
  • if last.offsetSign(first)<0, the range is decreasing.

A range for a recursive enumerable type is always increasing.

The span operator .. is an abbreviation for span():

for (i in min..max) { ... }
if (char in 'A'..'Z') { ... }

The span operator accepts the first and last values of the range. It may produce an increasing range:

0..5    // [0, 1, 2, 3, 4, 5]
0..0    // [0]

Or it may produce a decreasing range:

5..0    // [5, 4, 3, 2, 1, 0]
0..-5   // [0, -1, -2, -3, -4, -5]
Since 1.1.0
sumSource Codeshared Value sum<Value>({Value+} values)
given Value satisfies Summable<Value>

Given a nonempty stream of Summable values, return the sum of the values.

{Float+} values = ... ;
Float total = sum(values);

For the case of a possibly-empty stream, form a nonempty stream starting with the zero element (the additive identity).

{Float*} values = ... ;
Float total = sum { 0.0, *values };
See also product()
timesSource Codeshared Value times<Value>(Value x, Value y)
given Value satisfies Numeric<Value>

Multiply the given Numeric values.

(1..100).by(2).fold(1)(times<Integer>)
See also plus(), product()
uncurrySource Codeshared Return(*Tuple<Argument,First,Rest>) uncurry<Return, Argument, First, Rest>(Return(*Rest) f(First first))
given First satisfies Argument

Uncurries a function, returning a function with one parameter list, given a function with two parameter lists, where the first parameter list has exactly one parameter. The parameter list of the returned function has the parameter of the first parameter list of the original function, followed by all parameters of the second parameter list.

That is, if fun has type W(Y,Z)(X) then uncurry(fun) has type W(X,Y,Z).

See also curry(), compose()
unflattenSource Codeshared Return unflatten<Return, Args>(Return(*Args) flatFunction)(Args args)

Given a function with parameter types P1, P2, …, Pn, return a function with a single parameter of tuple type [P1, P2, ..., Pn].

That is, if fun has type W(X,Y,Z) then unflatten(fun) has type W([X,Y,Z]).

In the case of a variadic function, the returned function has a single parameter whose type is a sequence type or unterminated tuple type:

  • if the given function has a single variadic parameter of type S*, the returned function accepts [S*],
  • if the given function has a single variadic parameter of type S+, the returned function accepts [S+],
  • if the given function has multiple parameters with types P1, P2, …, Pn, S*, the returned function accepts [P1, P2, ..., Pn, S*], or
  • if the given function has multiple parameters with types P1, P2, …, Pn, S+, the returned function accepts [P1, P2, ..., Pn, S+].
See also flatten()
unzipSource Codeshared [Iterable<Head,Absent>, Iterable<Tail,Absent>] unzip<Element, Head, Tail, Absent>(Iterable<Tuple<Element|Head,Head,Tail>,Absent> tuples)
given Absent satisfies Null

Given a stream of tuples, return two streams. The first stream produces the first elements of the given tuples, and the second stream produces the remaining elements of the given tuples.

Thus:

tuples[i] == [unzip(tuples)[0][i], 
             *unzip(tuples)[1][i]]
unzipEntriesSource Codeshared [Iterable<Key,Absent>, Iterable<Item,Absent>] unzipEntries<Key, Item, Absent>(Iterable<Key->Item,Absent> entries)
given Key satisfies Object
given Absent satisfies Null

Given a stream of entries, return two streams. The first stream produces the keys of the given entries, and the second stream produces the items of the given entries.

Thus:

entries[i] == unzipEntries(entries)[0][i] 
           -> unzipEntries(entries)[1][i]
unzipPairsSource Codeshared [Iterable<First,Absent>, Iterable<Second,Absent>] unzipPairs<First, Second, Absent>(Iterable<[First, Second],Absent> pairs)
given Absent satisfies Null

Given a stream of pairs, return two streams. The first stream produces the first elements of the given pairs, and the second stream produces the second elements of the given pairs.

Thus:

pairs[i] == [unzipPairs(pairs)[0][i], 
             unzipPairs(pairs)[1][i]]
zipSource Codeshared Iterable<Tuple<Element|Head,Head,Tail>,HeadAbsent|TailAbsent> zip<Element, Head, Tail, HeadAbsent, TailAbsent>(Iterable<Head,HeadAbsent> heads, Iterable<Tail,TailAbsent> tails)
given HeadAbsent satisfies Null
given TailAbsent satisfies Null

Given a stream of values, and a stream of tuples, produce a new stream of tuples formed by prepending the values in the first stream to the tuples in the second stream. The length of the resulting stream is the length of the shorter of the two given streams.

Thus:

zip(heads, tails)[i] == [heads[i], *tails[i]]

for every 0<=i<smallest(heads.size,tails.size).

zipEntriesSource Codeshared Iterable<Key->Item,KeyAbsent|ItemAbsent> zipEntries<Key, Item, KeyAbsent, ItemAbsent>(Iterable<Key,KeyAbsent> keys, Iterable<Item,ItemAbsent> items)
given Key satisfies Object
given KeyAbsent satisfies Null
given ItemAbsent satisfies Null

Given two streams, form a new stream consisting of all entries where, for any given index in the resulting stream, the key of the entry is the element occurring at the same index in the first stream, and the item is the element occurring at the same index in the second stream. The length of the resulting stream is the length of the shorter of the two given streams.

Thus:

zipEntries(keys, items)[i] == keys[i] -> items[i]

for every 0<=i<smallest(keys.size,items.size).

zipPairsSource Codeshared Iterable<[First, Second],FirstAbsent|SecondAbsent> zipPairs<First, Second, FirstAbsent, SecondAbsent>(Iterable<First,FirstAbsent> firstElements, Iterable<Second,SecondAbsent> secondElements)
given FirstAbsent satisfies Null
given SecondAbsent satisfies Null

Given two streams, form a new stream consisting of all pairs where, for any given index in the resulting stream, the first element of the pair is the element occurring at the same index in the first stream, and the second element of the pair is the element occurring at the same index in the second stream. The length of the resulting stream is the length of the shorter of the two given streams.

Thus:

zipPairs(xs, ys)[i] == [xs[i], ys[i]]

for every 0<=i<smallest(xs.size,ys.size).

Interfaces
AnnotatedSource Codeshared Annotated

A program element that can be annotated.

AnnotationSource Codeshared Annotation

The supertype of all annotation classes.

Annotation classes

An annotation class must satisfy Annotation, OptionalAnnotation, or SequencedAnnotation and must be annotated final annotation. For example:

"An annotation class."
final annotation class Example(shared String description) 
      satisfies Annotation {}

Annotation classes which satisfy Annotation directly may be applied to any program element that supports annotations (see Annotated). In practice, annotation classes often satisfy OptionalAnnotation or SequencedAnnotation in order to prevent annotations being applied to inappropriate program elements.

Each initializer parameter of an annotation class must have one of the following types:

  • Integer, Float, Character, or String,
  • an enumerated type whose cases are all anonymous classes, such as Boolean,
  • a subtype of Declaration
  • an annotation class,
  • {T*} or [T*] where T is a legal annotation parameter type, or
  • any tuple type whose element types are legal annotation parameter types.

An initializer parameter of an annotation class may be variadic or defaulted.

Annotation constructors

An annotation constructor is simply a top level function, annotated with annotation whose return type is an annotation class type. For example:

"An annotation constructor."
annotation Example example(String description="") 
    => Example(description);

Each parameter of an annotation constructor must have one of the following types:

  • Integer, Float, Character, or String,
  • an enumerated type whose cases are all anonymous classes, such as Boolean,
  • a subtype of Declaration,
  • an annotation type,
  • {T*} or [T*] where T is a legal annotation constructor parameter type, or
  • any tuple type whose element types are legal annotation constructor parameter types.

A parameter of an annotation constructor may be variadic or defaulted.

The constructor must simply instantiate and return the annotation class, and there are strict rules about the arguments to the instantiation.

A given annotation class can have multiple annotation constructors.

BinarySource Codeshared Binary<Other>
given Other satisfies Binary<Other>

Abstraction of types that are conceptually a sequence of bits, and may be the subject of bitwise operations. A bit is a Boolean value. Bits are indexed from right to left, where 0 is the index of the least significant bit.

CallableSource Codeshared out Return(*in Arguments)

A reference to a function. The type arguments encode the Return of the function along with its Arguments. The parameter types are represented by a tuple type. Functions declared void are considered to have the return type Anything.

For example, the type of the anonymous function (Float x, Integer y) => x^y+1 is:

Callable<Float, [Float,Integer]>

which we usually abbreviate to Float(Float,Integer).

Likewise, the type of the function reference plus<Float> to the function plus() is:

Callable<Float, [Float,Float]>

which we abbreviate as Float(Float,Float).

A variadic function is represented using an unterminated tuple type. For example, the type of the function reference concatenate<Object> to the function concatenate() is:

Callable<Object[], [{Object*}*]>

which we usually abbreviate Object({Object*}*).

A function with defaulted parameters is represented using a union type. For example, the type of the method reference process.writeLine to the method process.writeLine() is:

Callable<Anything, [String]|[]>

which we usually abbreviate Anything(String=).

Finally, any type of form Callable<X,Y> may be abbreviated to X(*Y).

Any instance of Callable may be invoked by supplying a positional argument list:

Float(Float,Float) add = plus<Float>;
value four = add(2.0, 2.0);

or by supplying a tuple containing the arguments:

Float(Float,Float) add = plus<Float>;
[Float,Float] twoAndTwo = [2.0, 2.0];
value four = add(*twoAndTwo);

The type of the tuple must be assignable to the type argument of Arguments.

There is no reasonable and computationally decidable definition of value equality for a function reference. Therefore, the equals() method of an instance of Callable always returns false, and x==y always evaluates to false for any two function references x and y.

This interface may not be implemented by user-written code.

CategorySource Codeshared Category<in Element = Object>
given Element satisfies Object

Abstract supertype of objects that contain other values, called elements, where it is possible to efficiently determine if a given value is an element. A Category may not be finite, and its elements may not even be countable. Thus, unlike streams, the elements of a generic Category are not iterable.

Category models a mathematical set, but is distinct from the Set collection type which represents finite sets.

The in operator may be used to determine if a value belongs to a Category:

if (69 in 0..100) { ... }
assert (key->item in { for (n in 0..100) n.string->n**2 });

An object may be a Category of two different disjoint element types. For example, String is a Category of its Characters and of its substrings.

if ("hello" in "hello world") { ... }
assert ('.' in string);

Every meaningful Category is formed from elements with some equivalence relation. Ordinarily, that equivalence relation is value equality. Thus, ordinarily, x==y implies that x in cat == y in cat. But this contract is not required since it is possible to form a meaningful Category using a different equivalence relation. For example, an IdentitySet is a meaningful Category, where the equivalence relation is identity equality.

Since Null is not considered to have any meaningful equivalence relation, a Category may not contain the null value.

Note that even though Category<Element> is declared contravariant in its Element, most types that inherit Category are covariant in their element type, and therefore satisfy Category<Object>, resulting in some loss of typesafety. For such types, Category.contains() should return false for any value that is not an instance of the element type. For example, String is a Category<Object>, not a Category<Character|String>, and x in string evaluates to false for every x that is not a String or Character.

CollectionSource Codeshared Collection<out Element = Anything>

An iterable collection of elements of finite Iterable.size, with a well-defined notion of value equality. Collection is the abstract supertype of List, Map, and Set.

A Collection forms a Category of its elements, and is Iterable. The elements of a collection are not necessarily distinct when compared using Object.equals().

A Collection may be cloned. If a collection is immutable, it is acceptable that clone() produce a reference to the collection itself. If a collection is mutable, clone() should produce a collection containing references to the same elements, with the same structure as the original collection—that is, it should produce a shallow copy of the collection.

All Collections are required to support a well-defined notion of value equality, but the definition of equality depends upon the kind of collection. Equality for Maps and Sets has a quite different definition to equality for Lists. Instances of two different kinds of collection are never equal—for example, a Map is never equal to a List.

ComparableSource Codeshared Comparable<in Other>
given Other satisfies Comparable<Other>

The general contract for values whose magnitude can be compared. Comparable imposes a total ordering upon instances of any type that satisfies the interface.

If a type T satisfies Comparable<T>, then instances of T may be compared using the comparison operators <, >, <=, >=.

assert (x>=0.0);

A ternary comparison is useful for asserting lower and upper bounds.

assert (0.0<=x<1.0);

Finally, the compare operator <=> may be used to produce an instance of Comparison.

switch (x<=>y)
case (equal) {
    print("same same");
}
case (smaller) {
    print("x smaller");
}
case (larger) {
    print("y smaller");
}

The total order of a type must be consistent with the definition of equality for the type. That is, there are three mutually exclusive possibilities:

  • x<y,
  • x>y, or
  • x==y

(These possibilities are expressed by the enumerated instances smaller, larger, and equal of Comparison.)

The order imposed by Comparable is sometimes called the natural order of a type, to reflect the fact that any function of type Comparison(T,T) might determine a different order. Thus, some order-related operations come in two flavors: a flavor that depends upon the natural order, and a flavor which accepts an arbitrary comparator function. Examples are:

ConstrainedAnnotationSource Codeshared ConstrainedAnnotation<out Value = Annotation,out Values = Anything,in ProgramElement = Nothing,out Type = Anything>
given Value satisfies Annotation
given ProgramElement satisfies Annotated

An annotation constrained to appear only on certain program elements, and only with certain values.

This interface should never be satisfied directly by any annotation type. Instead, either OptionalAnnotation or SequencedAnnotation should be satisfied by the annotation type.

The type parameters encode information about the annotation type and its constraints:

  • Value represents the type of the annotation itself,
  • ProgramElement represents a constraint on the
    reference expression type of the annotated program element, for example, ClassDeclaration or Module, where Annotated means there is no constraint, and
  • Type is a constraint on the metamodel type of the annotated program element, for example, Function<Float,[Float,Float]> (ceylon.language.meta.model::Function), where Anything means there is no constraint, and that the program element need not have a metamodel type.
CorrespondenceSource Codeshared Correspondence<in Key,out Item = Anything>
given Key satisfies Object

Abstract supertype of objects which associate values with keys. A Correspondence<Key,Item> may be a viewed as a partial function from domain Key to range Item, where some Keys have no Item.

Correspondence does not satisfy Category, since in some cases—List, for example—it is convenient to consider the subtype a Category of its indexed items, and in other cases—Map, for example—it is convenient to treat the subtype as a Category of its entries.

The item corresponding to a given key may be obtained from a Correspondence using the item operator:

value bg = settings["backgroundColor"] else white;

The get() operation and item operator result in an optional type, to reflect the possibility that there may be no item for the given key.

CorrespondenceMutatorSource Codeshared CorrespondenceMutator<in Item>

A Correspondence that supports mutation of its constituent key/item associations. Items may be mutated via the assignment and item operators:

array[i] = i^2;

Every CorrespondenceMutator is either:

Most CorrespondenceMutators are also instances of Correspondence.

DestroyableSource Codeshared Destroyable

Abstract supertype of resources which are created at the beginning of a try statement and destroyed when the statement completes. Unlike an Obtainable resource, a single instance of Destroyable may not be reused between multiple try statements or multiple executions of the same try statement.

try (tx = Transaction()) {
    ...
}
  • The resource is instantiated before the body of the try statement is executed, and
  • Destroyable.destroy() is called when execution of the body of the try statement ends, even if an exception propagates out of the body of the try.
EmptySource Codeshared Empty

A sequence with no elements. The type Empty may be abbreviated [], and an instance is produced by the expression []. That is, in the following expression, none has type [] and refers to the value []:

[] none = [];

(Whether the syntax [] refers to the type or the value depends upon how it occurs grammatically.)

EnumerableSource Codeshared Enumerable<Other>
given Other satisfies Enumerable<Other>

Abstraction of ordinal types whose values may be used as endpoints of a span() or measure().

An Enumerable type is characterized by each element having well-defined offset and Enumerable.neighbour() functions. Given an instance x of an enumerable type X:

  • for any integer-valued offset, there is a unique neighbour y of X with that offset, and
  • if y is an instance of X, then there is a well-defined integer-valued offset of x from y.

The offset function must satisfy:

  • x.offset(x) == 0, and
  • x.successor.offset(x) == 1 if x!=x.successor.

The neighbour function must satisfy:

  • x.neighbour(0) == x,
  • x.neighbour(n-1) == x.neighbour(n).predecessor, and
  • x.neighbour(n+1) == x.neighbour(n).successor.

Of course, it follows that:

  • x.neighbour(-1) == x.predecessor, and
  • x.neighbour(1) == x.successor.

An enumerable type may be linear or recursive. If X is a linear enumerable type, then the offset function satisfies:

  • x.predecessor.offset(x) == -1 if x!=x.predecessor,
  • x.offset(y) == -y.offset(x) for any instance y of X, and
  • x.offset(y) == x.offset(z) + z.offset(y).

Otherwise, X is a recursive enumerable type with a finite list of enumerated instances of size count, and its offset and neighbour functions must satisfy:

  • x.neighbour(count)==x,
  • x.offset(y) >= 0 for any instance y of X, and
  • x.predecessor.offset(x) == count - 1.

A range of values of an enumerable type may be specified using:

  • the span operator, written first..last, or
  • the segment operator, written first:length.
ExponentiableSource Codeshared Exponentiable<This,Other>
given This satisfies Exponentiable<This,Other>
given Other satisfies Numeric<Other>

Abstraction of numeric types that may be raised to a power using the exponentiation operator x ^ n which accepts an instance of Exponentiable as its first operand, and an exponent as its second operand.

function exp(Float x) => e^x;

The exponentiation operation should obey the usual index laws, including:

  • x^0 == 1
  • x^1 == x
  • x^(-1) == 1/x
  • x^(m+n) == x^m * x^n
  • x^(m-n) == x^m / x^n
  • x^(m*n) == (x^m)^n
  • (x*y)^n == x^n * y^n

where 0 is the additive identity, and 1 is the multiplicative identity.

Note that in general, the type of the exponent may be different to the numeric type which is exponentiated. For example, a Rational number class might be a subtype of Exponentiable<Rational,Integer>, thus accepting only whole-number exponents.

IdentifiableSource Codeshared Identifiable

The abstract supertype of all types with a well-defined notion of identity. Values of type Identifiable may be compared using the === operator to determine if they are references to the same object instance.

For the sake of convenience, this interface defines a default implementation of value equality equivalent to identity. Of course, subtypes are encouraged to refine this implementation.

IndexedCorrespondenceMutatorSource Codeshared IndexedCorrespondenceMutator<in Element>

A CorrespondenceMutator which allows mutation of the item associated with a given integer index from a range of adjacent indices.

Many IndexedCorrespondenceMutators are Lists.

IntegralSource Codeshared Integral<Other>
given Other satisfies Integral<Other>

Abstraction of integral numeric types. That is, types with no fractional part, including Integer.

The division operation for integral numeric types results in a remainder. Therefore, integral numeric types have an operation, denoted by the remainder operator %, to determine the remainder of any division operation.

if (n%2==0) {
    print("Even!");
}

Division and the remainder operation should satisfy:

  • x == (x/y)*y + x%y

for any instance x and any instance y other than 0.

All Integral numeric types are also Enumerable, so ranges of integral values may be produced using the measure() and span() operators.

// Iterate from 0 to 100 inclusive
for (i in 0..100) {
    print("The square of ``i`` is ``i^2``");
}

// Iterate all indices of the array, 
// from 0 to array.size-1
for (i in 0:array.size) {
    print(array[i]);
}
InvertibleSource Codeshared Invertible<Other>
given Other satisfies Invertible<Other>

Abstraction of additive numeric types which support a unary operation -x producing the additive inverse of x. Every Invertible type supports a binary subtraction operation x-y.

Integer negativeOne = -1;
Float delta = x-y;

A concrete class that implements this interface should be a mathematical group. That is, it should have an additive identity, denoted 0, and satisfy:

  • 0+x == x+0 == x
  • x + -x == 0

Subtraction must be defined so that it is consistent with the additive inverse:

  • x - y == x + -y
IterableSource Codeshared Iterable<out Element = Anything,out Absent = Null>
given Absent satisfies Null

Abstract supertype of categories whose elements may be iterated. Iterable categories are often called streams. A stream is a source of Iterators, which produce the elements of the stream. A given element may occur more than once in a stream, that is, it may be produced more than once by a given iterator of the stream.

A stream may have null elements. That is, an iterator for the stream may produce the value null one or more times. For every non-null element of a given stream it, the expression element in it must evaluate to true. Thus, a stream is a Category of its non-null elements.

A finite stream is a stream whose iterators are exhaustible, that is, they eventually stop producing elements. A stream need not be finite, but its elements must be countable. That is, for any given element of the stream, every Iterator of the stream must eventually return the element, even if the iterator itself is not exhaustible. It is possible for a given element to occur a (countably) infinite number of times in a nonfinite stream. It may not, in general, be possible to even determine if an insteance of Iterable is finite.

For a nonfinite stream, certain operations of this interface either never terminate or result in an AssertionError.

A stream may be mutable, in which case two distinct iterators for the stream might not produce exactly the same elements. Furthermore, even an immutable stream might not have a well-defined order, and so the order in which elements are produced by the stream's iterator may not be stable. That is, the order may be different for two distinct iterators of the stream.

However, a stream has a well-defined set of elements, and so any two iterators for an immutable finite stream should eventually return the same elements. Furthermore, any two iterators for an immutable finite stream should eventually return exactly the same total number of elements, which must be the Iterable.size of the stream. For an immutable nonfinite stream, every element returned by a given iterator must eventually be returned by any other iterator of the stream.

A stream may be known to be nonempty:

  • The type Iterable<Element,Null>, usually abbreviated {Element*}, represents a possibly-empty stream.
  • The type Iterable<Element,Nothing>, usually abbreviated {Element+}, represents a nonempty stream.

Every iterator for a nonempty stream must produce at least one element.

A value list in braces produces a new instance of Iterable:

{String+} words = { "hello", "world" };

An instance of Iterable may be iterated using a for loop:

for (c in "hello world") { ... }

Comprehensions provide a convenient syntax for transforming streams:

{Integer+} lengths = { for (w in words) w.size };

The *. operator may be used to evaluate an attribute or invoke a method of the elements of the stream, producing a new stream:

{Integer+} lengths = words*.size;

Iterable and its subtypes define various operations that return other iterable objects. Such operations come in two flavors:

  • Lazy operations return a view of the receiving iterable object. If the underlying iterable object is mutable, then changes to the underlying object will be reflected in the resulting view. Lazy operations are usually efficient, avoiding memory allocation or iteration of the receiving iterable object.
  • Eager operations return an immutable object. If the receiving iterable object is mutable, changes to this object will not be reflected in the resulting immutable object. Eager operations are often expensive, involving memory allocation and iteration of the receiving iterable object.

Lazy operations are generally preferred, because they can be efficiently chained. For example:

string.filter((c) => c.letter||c.digit)
      .map(Character.uppercased)

is much less expensive than:

string.select((c) => c.letter||c.digit)
      .collect(Character.uppercased)

Furthermore, it is always easy to produce a new immutable iterable object given the view produced by a lazy operation. For example:

[ *string.filter((c) => c.letter||c.digit)
         .map(Character.uppercased) ]

However, there are certain scenarios where an eager operation is more useful, more convenient, or no more expensive than a lazy operation, including:

  • sorting operations, for example Iterable.sort(), which are eager by nature,
  • operations which result in a subset or subrange of the receiving stream, where structural sharing would or could result in unnecessary memory retention.

Certain operations come in both lazy and eager flavors, for example:

Lazy operations normally return an instance of Iterable, or even a List, Map, or Set. Eager operations usually return a sequence. The method Iterable.sequence() materializes the current elements of a stream into a sequence.

There is no meaningful generic definition of equality for streams. For some streams—for example, Lists—order is significant; for others—for example, Sets—order is not significant. Therefore, unlike Collection and its subtypes, Iterable does not define nor require any form of value equality, and some streams simply do not support value equality. It follows that the == operator should not be used to compare generic streams, unless the streams are known to share some additional structure.

To compare the elements of two streams, taking order into account, use the function corresponding().

{Float*} xs = ... ;
{Float*} ys = ... ;
Boolean same = corresponding(xs, ys);
IteratorSource Codeshared Iterator<out Element>

Produces the elements of a stream. For example, this class has an Iterator that produces the integers from min to max:

class IntegerIterable(Integer min, Integer max) 
       satisfies {Integer*} {
   iterator() => object satisfies Iterator<Integer> {
       variable value i = min;
       next() => i<=max then i++ else finished;
   };
}

An iterator is exhausted when Iterator.next() produces the value finished.

KeyedCorrespondenceMutatorSource Codeshared KeyedCorrespondenceMutator<in Key,in Item>
given Key satisfies Object

A CorrespondenceMutator which allows mutation of the item associated with an existing key, and creation of a new key/item association.

Many KeyedCorrespondenceMutators are Maps.

ListSource Codeshared List<out Element = Anything>

A collection in which every element has a unique non-negative integer index. The elements of a nonempty list are indexed starting with 0 at the List.first element of the list, and ending with the index List.lastIndex at the List.last element of the list.

  • For any nonempty list, lastIndex==size-1.
  • For an empty list, size==0 and the lastIndex is null.

Thus, the range of indexes of the list is formed by the expression 0:list.size.

A List is a Collection of its elements, and a Correspondence from indexes to elements.

Every list has a well-defined and stable iteration order. An List.iterator() of a nonempty list is required to return the elements of the list in order of increasing index, beginning with the element at index 0, and ending with the element at index lastIndex. Thus, every iterator of an immutable list produces exactly the same elements in exactly the same order.

Direct access to a list element by index produces a value of optional type. The following idiom may be used instead of upfront bounds-checking, as long as the list element type is a non-null type:

if (exists char = "hello world"[index]) { 
    //do something with char
}
else {
    //out of bounds
}

When an algorithm guarantees that a list contains a given index, the following idiom may be used:

assert (exists char = "hello world"[index]);
//do something with char

To iterate the indexes of a List, use the following idiom:

for (i->char in "hello world".indexed) { ... }

Strings, sequences, tuples, and arrays are all Lists, and are all of fixed length. Variable-length mutable Lists are also possible.

MapSource Codeshared Map<out Key = Object,out Item = Anything>
given Key satisfies Object

A collection which maps keys to items, where a key can map to at most one item. Each such mapping may be represented by an Entry. Thus, each distinct key occurs in at most one entry. Two non-identical keys are considered distinct only if they are unequal, according to their own definition of value equality.

A Map is a Collection of its Entrys, and a Correspondence from keys to items.

A new Map may be obtained by calling the function map().

value settings = map { "lang"->"en_AU", "loc"->"ES" };

The emptyMap is a Map with no entries.

The presence of an entry in a map may be tested using the in operator:

if ("lang"->"en_AU" in settings) { ... }

The entries of the map may be iterated using for:

for (key->item in settings) { ... }

The item for a key may be obtained using the item operator:

String lang = settings["lang"] else "en_US";

An implementation of Map may compare keys for equality using Object.equals() or Comparable.compare().

NumberSource Codeshared Number<Other>
given Other satisfies Number<Other>

Abstraction of numeric types with a natural total order, including the built-in numeric types Integer and Float.

A Number has a well-defined Number.magnitude together with a Number.sign of type Integer, defined for any instance x as follows:

  • if x==0 then x.sign==0 and x.magnitude==0,
  • if x>0 then x.sign==1 and x.magnitude==x, or
  • if x<0 then x.sign==-1 and x.magnitude==-x,

where 0 is the additive identity of the numeric type.

Not every value commonly considered to be a “number” is a Number. For example, complex numbers aren't Numbers since they don't have a total order.

NumericSource Codeshared Numeric<Other>
given Other satisfies Numeric<Other>

Abstraction of numeric types with the usual binary operations:

  • addition, x + y,
  • subtraction, x - y,
  • multiplication, x * y, and
  • division, x / y, along with
  • additive inverse -x.

A concrete class which implements this interface should be a mathematical ring. That is:

  • both addition, +, and multiplication, *, should be associative and commutative,
  • there should be additive and multiplicative identities, denoted 0 and 1 respectively, satisfying x+0 == x and x*1 == x,
  • every instance x should have an additive inverse -x, satisfying x + -x == 0, and
  • multiplication should distribute over addition, satisfying x*(y+z) == x*y + x*z.

It is preferred, but not required, that the class be a mathematical field. That is, in addition to the above:

  • every instance x such that x!=0 should have a multiplicative inverse 1/x, satisfying x * 1/x == 1.

For numeric types which are not fields, for example, Integer, there is still a division operation, which is understood to produce a remainder. The division operation should satisfy:

  • x*y / y == x

for any instance y other than 0.

For numeric types which are fields, division never produces a remainder, and division should additionally satisfy:

  • x/y * y == x

for any instance y other than 0.

Some numeric types, for example complex numbers, do not have a total order. Numeric types with a total order also satisfy Number.

ObtainableSource Codeshared Obtainable

Abstract supertype of resources which may be obtained at the beginning of a try statement and then released when the statement completes. Unlike a Destroyable resource, a single instance of Obtainable may be reused between multiple try statements or multiple executions of the same try statement.

Lock lock = ... ;
try (lock) {
    ...
}
  • Obtainable.obtain() is called before the body of the try statement is executed, and
  • Obtainable.release() is called when execution of the body of the try statement ends, even if an exception propagates out of the body of the try.

A class which satisfies Obtainable may impose constraints on the ordering and nesting of invocations of obtain() and release(). For example, it may be not be possible to obtain a resource that has already been obtained. Those methods should produce an AssertionError when any such constraint is violated.

OptionalAnnotationSource Codeshared OptionalAnnotation<out Value,in ProgramElement = Annotated,out Type = Anything>
given Value satisfies OptionalAnnotation<Value,ProgramElement,Type>
given ProgramElement satisfies Annotated

An annotation that may occur at most once at a given program element and only on certain program elements.

An optional annotation is declared simply by having the annotation class satisfy OptionalAnnotation instead of Annotation. For example the following would only be allowed on class declarations:

final annotation class ExampleClass() 
        satisfies OptionalAnnotation<Example, ClassDeclaration> {}

At runtime a Declaration instance can be queried for its OptionalAnnotations of a certain type using annotations() or optionalAnnotation().

OrdinalSource Codeshared Ordinal<out Other>
given Other satisfies Ordinal<Other>

Abstraction of ordinal types, that is, of types where each instance has a Ordinal.successor and Ordinal.predecessor, such as:

  • types which represent or are isomorphic to the mathematical integers, for example, Integer and other Integral numeric types, and even Character, along with
  • enumerated types which are isomorphic to the mathematical integers under modular arithmetic, for example, the days of the week, and
  • enumerated types which are isomorphic to a bounded range of integers, for example, a list of priorities.

The increment operator ++ and decrement operator -- are defined for all types which satisfy Ordinal.

function increment() {
    count++;
}

Many ordinal types have a total order. If an ordinal type has a total order, then it should satisfy:

  • x.successor >= x, and
  • x.predecessor <= x.

An ordinal enumerated type X with a total order has well-defined maximum and minimum values where minimum<x<maximum for any other instance x of X. Then the successor and predecessor operations should satisfy:

  • minimum.predecessor==minimum, and
  • maximum.successor==maximum.
RangedSource Codeshared Ranged<in Index,out Element,out Subrange>
given Subrange satisfies Ranged<Index,Element,Subrange>

Abstract supertype of ranged streams mapping a range of discrete indices to elements of the stream, and supporting operations that produce a subrange of indexed elements. The type parameter Subrange abstracts the type of the resulting subrange. A subrange may be obtained from an instance of Ranged using the span and measure operators.

Typically, the Subrange type is the same as the ranged type itself. But this is not required. For example, the subranges of a StringBuilder are Strings.

Often, in a List or sorted map for example, an index and its element are distinct values. Sometimes, in a sorted set for example, the index and element are identical.

The span operator accepts the first and last indices of the subrange.

print("hello world"[0..4]); //prints "hello"
print("hello world"[6..6]); //prints "w"

If the last index is smaller than the first index, the subrange is reversed.

print("hello world"[4..0]); //prints "olleh"

If the range of indices identified by the first and last indices is outside the range of indices of this object, an empty subrange is produced.

print("hello world"[-5..-1]); //prints ""
print("hello world"[11..11]); //prints ""

The first index may be omitted, implying that the subrange extends forward from the smallest possible index (in this case runtime.minIntegerValue) to the given index.

print("hello world"[...4]) //prints "hello"

If the first index is before the first index of this object, the first index of the object is used.

print("hello world"[-5...]); //prints "hello world"

The last index may be omitted, implying that the subrange extends forward from the given index to the largest possible index (in this case runtime.maxIntegerValue).

print("hello world"[6...]) //prints "world"

If the last index is after the last index of this object, an empty subrange is produced. (A reversed subrange is never produced.)

print("hello world"[11...]); //prints ""

The measure operator accepts the first index and maximum length of the subrange.

print("hello world"[6:5]) //prints "world"
print("hello world"[6:0]) //prints ""

If the length is nonpositive, the subrange is empty. If the range of indices identified by the first index and length is outside the range of indices of this object, an empty subrange is produced. (A reversed subrange is never produced.)

print("hello world"[-3:3]) //prints ""
print("hello world"[11:3]) //prints ""
print("hello world"[6:-3]) //prints ""

The span and measure operations must be consistent. That is, for every pair of indices x and y in the ranged object ranged such that y does not occur before x and the span ranged[x..y] has length n:

  • ranged[x..y]==ranged[x:n].
ResourceSource Codeshared Resource

A file packaged within a module. A Resource may be obtained by calling Module.resourceByPath(), passing a path that identifies the resource file.

The resource file itself must be placed in a resource directory at compilation time, in a subdirectory corresponding to the module to which the resource belongs. The compiler is responsible for packaging the resource file in a location accessible to the program at runtime:

  • In the case of a module compiled for execution on the JVM, the resource file will be included in the .car archive.
  • In the case of compilation to JavaScript, the resource file will be copied to a module-resources directory in the module repository.

Suppose the following code occurs in a module named com.redhat.example:

assert (exists resource 
   = `module`.resourceByPath("file.txt"));
print(resource.textContent());

Then the resource named file.text should be placed in the subdirectory com/redhat/example/ of the resource directory.

Paths with no leading / are relative to the module's subdirectory of the resource directory. Alternatively, a resource may be identified by a fully-qualified path beginning with /, for example:

assert (exists resource 
   = `module`.resourceByPath("/com/redhat/example/file.txt"));
print(resource.textContent());
ScalableSource Codeshared Scalable<in Scale,out Value>
given Scale satisfies Numeric<Scale>
given Value satisfies Scalable<Scale,Value>

Abstract supertype of types that support scaling by a numeric factor. Examples of such types include vectors and matrices. The scale operator a ** x accepts a scale factor as its first operand, and an instance of Scalable as its second operand.

Vector scaled = 2.0 ** Vector(x,y,z);

Concrete classes which implement this interface should satisfy:

  • x == 1**x
  • a ** (b ** x) == a*b ** x

where 1 denotes the multiplicative identity of the numeric scaling type.

Concrete classes which implement this interface are encouraged to also satisfy Invertible, in which case, the following identity should be satisfied:

  • -x == -1**x

Concrete classes which implement this interface and which also satisfy Summable should satisfy:

  • x+x == 2**x
  • a ** (x+y) == a**x + a**y

The Scale must be a numeric type, but is not required to be Number, since a complex number scaling type should be allowed.

SearchableListSource Codeshared SearchableList<Element>

A List which can be efficiently searched for occurrences of a given element, or for inclusions of a given sublist of elements. This interface provides operations for finding:

  • occurrences of a single value in the list, and
  • inclusions of a given sublist of values in the list.

Occurrences and inclusions are identified by a list index at which the value or sublist of values occurs in the list. In the case of an inclusion, it is the index of the first matching value from the sublist.

Inclusions may overlap. For example:

"yoyoyoyoyo".inclusions("yoy")

produces the stream { 0, 2, 4, 6 }.

An empty list is considered to be included at every index, including the index List.size at the very end of the list. Thus:

"hello".inclusions("")

produces the stream { 0, 1, 2, 3, 4, 5 }, with 6 inclusions in a string of length 5.

In particular:

  • "".inclusions("x") is the empty stream {}, but
  • "".inclusions("") is the stream { 0 }.
SequenceSource Codeshared Sequence<out Element = Anything>

A nonempty, immutable sequence of values. The type Sequence<Element> may be abbreviated [Element+].

Given a possibly-empty sequence of type [Element*], the if (nonempty ...) construct, or, alternatively, assert (nonempty ...), may be used to narrow to a sequence type to a nonempty sequence type:

[Integer*] nums = ... ;
if (nonempty nums) {
    Integer first = nums.first;
    Integer max = max(nums);
    [Integer+] squares = nums.collect((Integer i) => i**2));
    [Integer+] sorted = nums.sort(byIncreasing((Integer i) => i));
}

Operations like first, max(), collect(), and sort(), which polymorphically produce a nonempty or non-null output when given a nonempty input are called emptiness-preserving.

Sequence has the following subtypes:

SequencedAnnotationSource Codeshared SequencedAnnotation<out Value,in ProgramElement = Annotated,out Type = Anything>
given Value satisfies SequencedAnnotation<Value,ProgramElement,Type>
given ProgramElement satisfies Annotated

An annotation that may occur multiple times at a given program element, and only on certain program elemenets.

A sequenced annotation is declared simply by having the annotation class satisfy SequencedAnnotation instead of Annotation. For example the following would only be allowed on class declarations, functions or methods:

alias ExecutableDeclaration 
       => ClassOrInterfaceDeclaration|FunctionDeclaration;
"Documents a pattern in which the annotated element 
 particpates."
shared final annotation class Pattern(String name) 
        satisfies SequencedAnnotation<Pattern, ExecutableDeclaration> {}

At runtime a Declaration instance can be queried for its SequencedAnnotations of a certain type using annotations() or sequencedAnnotations().

SequentialSource Codeshared Sequential<out Element = Anything>

A possibly-empty, immutable sequence of values. The type Sequential<Element> may be abbreviated [Element*] or Element[].

Sequential has two enumerated subtypes:

  • Empty, abbreviated [], represents an empty sequence, and
  • Sequence<Element>, abbreviated [Element+] represents a non-empty sequence, and has the very important subclass Tuple.
SetSource Codeshared Set<out Element = Object>
given Element satisfies Object

A collection in which each distinct element occurs at most once. Two non-identical values are considered distinct only if they are unequal, according to their own definition of value equality.

A Set is a Collection of its elements. Sets may not have null elements.

A new Set may be obtained by calling the function set().

value words = set { "hello", "world" };
value greetings = set { "hello", "goodbye", "hola", "adios" };

The emptySet is a Set with no elements.

Sets may be the subject of the binary union, intersection, and complement operators |, &, and ~.

value greetingsInWords = words & greetings;
value allWords = words | greetings;

An implementation of Set may compare elements for equality using Object.equals() or Comparable.compare().

SummableSource Codeshared Summable<Other>
given Other satisfies Summable<Other>

Abstraction of types which support a binary addition operator x + y. For numeric types, this is just familiar numeric addition. For String, it is string concatenation.

Integer next = current + 1;
String helloWorld = "hello" + " " + "world";

A concrete class that implements this interface should be a mathematical semigroup. That is, the addition operation should be associative, satisfying:

  • (x+y)+z == x+(y+z)

A Summable type might be a monoid, that is, a semigroup with an additive identity element, usually denoted 0, but this is not required. For example:

  • String is a monoid with identity element "",
  • Float is a monoid with identity element 0.0, and
  • Integer is a monoid with identity element 0.

For any monoid, the addition operation must satisfy:

  • x + 0 == x
UsableSource Codeshared Usable

Abstract supertype of resources whose lifecyle may be managed by the try statement.

Classes
AnythingSource Codeshared abstract Anything

The abstract supertype of all types. A value of type Anything may be a definite value of type Object, or it may be the null value. A method declared void is considered to have the return type Anything.

Note that the bottom type Nothing, representing the intersection of all types, is a subtype of all types.

ArraySource Codeshared final Array<Element>

A fixed-sized array of mutable elements. An empty array is an array of size 0. An array may be created with a list of initial elements, or, via the constructor Array.ofSize(), with a size and single initial value for all elements.

value array = Array { "hello", "world" };
value ints = Array.ofSize(1k, 0);

Arrays are mutable. Any element of an array may be set to a new value.

value array = Array { "hello", "world" };
array[0] = "goodbye";

Arrays are lists and support all operations inherited from List, along with certain additional operations for efficient mutation of the array: Array.set(), Array.swap(), Array.move(), Array.sortInPlace(), Array.reverseInPlace(), and Array.copyTo().

This class is provided primarily to ease interoperation with Java, and for some performance-critical low-level programming tasks.

On the JVM, for “primitive” element types Integer, Float, Byte, Character, and Boolean, Array is easily the most efficient sort of List in Ceylon. However, certain optimizations made by the compiler are impossible if the Array is assigned to a more generic type such as Iterable. Peak efficiency is obtained for algorithms coded to the static type Array.

Furthermore, Array is itself a compromise between raw performance, polymorphism, and portability. An instance of the Java primitive array type java.lang.LongArray (written long[] in Java) exhibits superior micro-level performance to an Array<Integer>, but:

  • is not a List, and
  • is not available except when compiling for the JVM.

Fortunately, given a Java primitive array, it's easy to obtain an Array backed by the primitive array:

//unportable JVM-specific code 
LongArray longArray = LongArray(size);
Array<Integer> array = longArray.integerArray;
ArraySequenceSource Codeshared final ArraySequence<out Element>

A Sequence backed by an Array.

Since Arrays are mutable, this class is private to the language module, where we can be sure the Array is not modified after the ArraySequence has been initialized.

BasicSource Codeshared abstract Basic

The default superclass when no superclass is explicitly specified using extends. For the sake of convenience, this class inherits Identifiable along with its default definition of value equality. Classes which aren't Identifiable should directly extend Object.

BooleanSource Codeshared abstract Boolean

A type capable of representing the values true and false of Boolean logic.

ByteSource Codeshared final Byte

An 8-bit byte. A Byte value represents a congruence class of integers modulo 256, and may be interpreted as:

Byte is not considered a full numeric type, supporting only:

  • bitwise operations, and
  • addition and subtraction modulo 256.

Bytes with modular addition form a mathematical group. Thus, every byte b has an additive inverse -b where:

(-b).signed == -b.signed
(-b).unsigned == b.unsigned==0 then 0 else 256 - b.unsigned

Byte is a recursive enumerable type. For example, the range:

254.byte .. 1.byte

contains the values 254.byte, 255.byte, 0.byte, 1.byte.

Byte does not have a total order because any such order would:

  • be inconsistent with the definition of Byte.successor and Byte.predecessor under modular addition, and
  • would depend on interpretation of the Byte value as signed or unsigned.

Thus, to compare the magnitude of two bytes, it is necessary to first convert them to either their signed or unsigned integer values.

Bytes are useful mainly because they can be efficiently stored in an Array.

CharacterSource Codeshared final Character

A 32-bit Unicode character.

Literal characters may be written between single quotes:

' '
'\n'
'\{#03C0}'
'\{GREEK SMALL LETTER PI}'

Every Character has a unique Integer-valued Unicode code point.

Integer piCodePoint = '\{GREEK SMALL LETTER PI}'.integer; // #03C0
Character pi = #03C0.character; // GREEK SMALL LETTER PI

Characters are Enumerable, so character ranges may be produced using the measure() and span() operators.

value lowerLatinLetters = 'a'..'z';
value upperLatinLetters = 'A':26;

Characters have a natural order determined by their Unicode code points. So, for example, 'a'<'b', since 'a'.integer<'b'.integer.

ComparisonSource Codeshared abstract Comparison

The result of a comparison between two Comparable objects: larger, smaller, or equal.

ContextualSource Codeshared Contextual<Element>

Stores values local to the current thread of execution meaning that each thread or process that accesses these values get to see their own copy. If the underlying platform does not support threading the practical effect of this class is no different than using a local value.

Setting a value is done by creating an instance of Contextual.Using, passing it the required value, or a function that will return the needed value when necessary, and passing it to a try-resource statement.

If a function is used to set the value then that value will be retrieved the moment the try-resource block is entered. If the same Using is re-used then the value will be refreshed by calling the function again.

When entering a try-resource block any previous value is stored and then restored at the end of the block so nested try-resource blocks are possible.

Retrieving the value is done using get(). Doing so when no try-resource statement is active will result in an assertion exception.

An example:

Contextual<String> stringValue = Contextual<String>();
Contextual<Integer> intValue = Contextual<Integer>();
try (stringValue.Using("foo"),
        intValue.Using(system.milliseconds)) {
    print(stringValue.get()); // prints "foo"
    print(intValue.get());    // prints the current time in ms
    try (stringValue.Using("bar")) {
        print(stringValue.get()); // prints "bar"
        print(intValue.get());    // prints same number as before
    }
}

NB: This example only shows how to use Contextual and does not show anything thread-related.

EntrySource Codeshared final Entry<out Key,out Item>
given Key satisfies Object

A pair containing a key and an associated value called the item. Used primarily to represent the elements of a Map. The type Entry<Key,Item> may be abbreviated Key->Item. An instance of Entry may be constructed using the -> operator:

String->Person entry = person.name->person;
FinishedSource Codeshared abstract Finished

The type of the value that indicates that an Iterator is exhausted and has no more values to return.

FloatSource Codeshared final Float

An IEEE 754 64-bit floating point number. A Float is capable of approximately representing numeric values between:

  • 2-1022, approximately 1.79769×10308, and
  • (2-2-52)×21023, approximately 5×10-324.

Zero is represented by distinct instances +0.0, -0.0, but these instances are equal. -0.0 can be distinguished from +0.0 using f == 0.0 && f.strictlyNegative.

In addition, the following special values exist:

As required by the IEEE standard no undefined value is equal to any other value, nor even to itself. Thus, the definition of Float.equals() for Float violates the general contract defined by Object.equals().

A floating point value with a zero Float.fractionalPart is considered equal to its Float.integer part.

Literal floating point values are written with a decimal point and, optionally, a magnitude or exponent:

1.0
1.0E6
1.0M
1.0E-6
1.0u

In the case of a fractional magnitude, the decimal point is optional. Underscores may be used to group digits into groups of three.

IntegerSource Codeshared final Integer

An exact representation of a positive whole number, negative whole number, or zero. The largest and smallest representable values are platform-dependent:

  • For the JVM runtime, integer values between -263 and 263-1 may be represented without overflow.
  • For the JavaScript runtime, integer values with a magnitude no greater than 253 may be represented without loss of precision.

Overflow or loss of precision occurs silently (with no exception raised).

An integer is considered equal to its Integer.float representation, if that exists. That is, for every integer int, either int.float throws an OverflowException, or the expression int.float==int evaluates to true.

An integer is representable as a sequence of bits. Not all of the bits in the representation may be addressed by the methods inherited from Binary:

  • For the JVM runtime, the bits at all indices (0 to 63) are addressable.
  • For the JavaScript runtime, the bits at indices 0 to 31 are addressable.

Literal integers may be written in decimal, hexadecimal, or binary notation:

8660
#21D4
$10000111010100

Underscores may be used to group digits:

8660
#21_D4
$10_0001_1101_0100
NullSource Codeshared abstract Null

The type of the null value. Any union type of form Null|T is considered an optional type, whose values include null. Any type of this form may be written as T? for convenience.

The if (exists ... ) construct, or, alternatively, assert (exists ...), may be used to narrow an optional type to a definite type, that is, a subtype of Object:

String? firstArg = process.arguments.first;
if (exists firstArg) {
    print("hello " + firstArg);
}

The else operator evaluates its second operand if and only if its first operand is null:

String name = process.arguments.first else "world";

The then operator evaluates its second operand when its first operand evaluates to true, and produces null otherwise:

Float? diff = x>=y then x-y;

The ?. operator may be used to evaluate an attribute or invoke a method of an optional type, evaluating to null when the receiver is missing:

value [firstName, lastName] =
        let (fullName = process.arguments.first?.trimmed,
             bits = fullName?.split()?.sequence() else []) 
                [bits[0], bits[1]];
assert (exists firstName, exists lastName);

No equivalence relation is defined for Null. In particular, neither null==null nor null===null are considered meaningful. Therefore, Null is neither Identifiable, nor does it define value equality.

ObjectSource Codeshared abstract Object

The abstract supertype of all types representing definite values. Any two values which are assignable to Object may be compared for value equality using the == and != operators, even if the values are of different concrete type:

true == false
1 == "hello world"
"hello"+" "+"world" == "hello world"
Singleton("hello world") == ["hello world"]

However, since Null is not a subtype of Object, the value null cannot be compared to any other value using the == operator. Thus, value equality is not defined for optional types. This neatly bypasses the problem of deciding the value of the expression null==null, which is simply illegal.

A concrete subclass of Object must refine Object.equals() and Object.hash (or inherit concrete refinements), providing a concrete definition of value equality for the class.

In extreme cases it is acceptable for two values to be equal even when they are not instances of the same class. For example, the Integer value 1 and the Float value 1.0 are considered equal. Except in these extreme cases, instances of different classes are considered unequal.

RangeSource Codeshared abstract Range<Element>
given Element satisfies Enumerable<Element>

A range of adjacent Enumerable values. Two values of an enumerable type are considered adjacent if their offset is of unit or zero magnitude. Thus, a Range is a list of values where for every integer index where both index and index+1 fall within the indices of the range:

range[index+1].offset(range[index]).magnitude <= 1

A range is always nonempty, containing at least one value. Thus, it is a Sequence.

A sequence of adjacent values may be represented very efficiently in memory, either:

  • via its endpoints, first..last, or
  • via an endpoint and length, first:size.

Furthermore, certain operations are much more efficient than for other lists, assuming that the enumerable type has efficient neighbour and offset functions.

The functions makeSpan() and makeMeasure(), and corresponding operators .. and : are used to create new instances of Range.

SingletonSource Codeshared final Singleton<out Element>

A Sequence with exactly one Singleton.element, which may be null.

StringSource Codeshared final String

A string of characters. Each character in the string is a 32-bit Unicode character. The internal UTF-16 encoding is hidden from clients.

Literal strings may be written between double quotes:

"hello world"
"\r\n"
"\{#03C0} \{#2248} 3.14159"
"\{GREEK SMALL LETTER PI} \{ALMOST EQUAL TO} 3.14159"

Alternatively, a verbatim string may be written between tripled double quotes.

The empty string, "", is a string with no characters.

A string is a Category of its String.characters, and of its substrings:

'w' in greeting 
"hello" in greeting

Strings are summable:

String greeting = "hello" + " " + "world";

They are efficiently iterable:

for (char in "hello world") { ... }

They are lists of characters:

value char = "hello world"[5];

They are ranged:

String who = "hello world"[6...];

Note that since string[index] evaluates to the optional type Character?, it is often more convenient to write string[index..index], which evaluates to a String containing a single character, or to the empty string "" if index refers to a position outside the string.

It is easy to use comprehensions to transform strings:

String { for (s in "hello world") if (s.letter) s.uppercased }

Since a String has an underlying UTF-16 encoding, certain operations are expensive, requiring iteration of the characters of the string. In particular, size requires iteration of the whole string, and get(), span(), and measure() require iteration from the beginning of the string to the given index.

StringBuilderSource Codeshared final StringBuilder

Builder utility for constructing strings by incrementally appending strings or characters.

value builder = StringBuilder();
builder.append("hello");
builder.appendCharacter(' ');
builder.append("world");
String hello = builder.string; //hello world
TupleSource Codeshared final Tuple<out Element,out First,out Rest = []>
given First satisfies Element

A tuple is a typed linked list. Each instance of Tuple represents the value and type of a single link. The attributes first and rest allow us to retrieve a value from the list without losing its static type information.

value point = Tuple(0.0, Tuple(0.0, Tuple("origin", [])));
Float x = point.first;
Float y = point.rest.first;
String label = point.rest.rest.first;

Usually, we abbreviate code involving tuples.

[Float,Float,String] point = [0.0, 0.0, "origin"];
Float x = point[0];
Float y = point[1];
String label = point[2];

A list of types enclosed in brackets is an abbreviated tuple type. An instance of Tuple may be constructed by surrounding a value list in brackets:

[String,String] words = ["hello", "world"];

The index operator with a literal integer argument is a shortcut for a chain of evaluations of rest and first. For example, point[1] means point.rest.first.

A terminated tuple type is a tuple where the type of the last link in the chain is Empty. An unterminated tuple type is a tuple where the type of the last link in the chain is Sequence or Sequential. Thus, a terminated tuple type has a length that is known statically. For an unterminated tuple type only a lower bound on its length is known statically.

Here, point is an unterminated tuple:

String[] labels = ... ;
[Float,Float,String*] point = [0.0, 0.0, *labels];
Float x = point[0];
Float y = point[1];
String? firstLabel = point[2];
String[] allLabels = point[2...];
emptySource Codeshared empty

A sequence with no elements, abbreviated []. The unique instance of the type [].

emptyIteratorSource Codeshared emptyIterator

An iterator that returns no elements.

emptyMapSource Codeshared emptyMap

An immutable Map with no entries.

emptySetSource Codeshared emptySet

An immutable Set with no elements.

equalSource Codeshared equal

The value is exactly equal to the given value.

falseSource Codeshared false

A value representing falsity in Boolean logic.

finishedSource Codeshared finished

A value that indicates that an Iterator is exhausted and has no more values to return.

languageSource Codeshared language

Contains information about the Ceylon language version.

largerSource Codeshared larger

The value is larger than the given value.

nullSource Codeshared null

The null value.

operatingSystemSource Codeshared operatingSystem

Represents the operating system on which the current process is running.

processSource Codeshared process

Represents the current process (instance of the virtual machine).

runtimeSource Codeshared runtime

Represents the machine and virtual machine on which the current process is executing.

Holds information about runtime name, version and about inherent limitations like minimum/maximum values that can be represented by the runtime.

smallerSource Codeshared smaller

The value is smaller than the given value.

systemSource Codeshared system

Represents the system on which the current process is executing.

Holds information about system time and locale.

trueSource Codeshared true

A value representing truth in Boolean logic.

Exceptions
AssertionErrorSource Codeshared AssertionError

An error that occurs due to an incorrectly written program. An instance is thrown when an assertion fails, that is, when a condition in an assert statement evaluates to false at runtime.

The assertion

"x must be positive"
assert (x>0);

has almost the same effect as this if statement

if (!x>0) {
    throw AssertionError("x must be positive");
}
ExceptionSource Codeshared Exception

The supertype of all unexpected transient failures. An Exception is usually unrecoverable from the point of view of the immediate caller of an operation.

For example, code that interacts with a relational database isn't typically written to recover from transaction rollback or loss of network connectivity. However, these conditions aren't completely unrecoverable from the point of view of the program's generic exception handling infrastructure. Therefore, they are best treated as Exceptions.

A subclass of Exception represents a more specific kind of problem, and may define additional attributes which propagate information about problems of that kind.

InitializationErrorSource Codeshared InitializationError

Assertion failure that occurs when a value reference could not be initialized, including when:

  • a toplevel value could not be initialized due to recursive dependencies upon other toplevel values,
  • an uninitialized late() value is evaluated,
  • an initialized late but non-variable value is reassigned.
OverflowExceptionSource Codeshared OverflowException

Thrown when a mathematical operation caused a number to overflow from its bounds, or when a numeric narrowing conversion fails because the number cannot be represented within the bounds of the narrower type.

Note that:

  • arithmetic operations on Integers result in silent overflow (JVM) or loss of precision (JavaScript), and thus never result in an OverflowException, and,
  • likewise, arithmetic operations on Float produce the value infinity instead of overflowing.
ParseExceptionSource Codeshared ParseException

Represents failure of an attempt to parse a string representation.

ThrowableSource Codeshared abstract Throwable

The abstract supertype of values indicating exceptional conditions. An exception may be raised using the throw statement, and handled using the catch clause of the try statement. An instance of Throwable may be passed from throw to catch.

void tryToDoIt() {
    if (canDoIt()) {
        doIt();
    }
    else {
        throw CantDoIt(); //the Throwable
    }
}

try {
    tryToDoIt();
}
catch (CantDoIt e) {
    e.printStackTrace();
}

An instance of Throwable represents a problem, typically an unexpected failure. Either:

  • a unrecoverable error in the program, especially an AssertionError, or
  • a transient, and possibly-recoverable Exception.

The use of the exceptions facility to manage expected failures, that is, failures that are usually handled by the immediate caller of an operation, is discouraged. Instead, the failure should be represented as a return value of the operation being called.

For example, nonexistence of a file should not result in an exception. Instead, an openFile() operation should return the type File?, where a null return value indicates nonexistence. On the other hand, failure to read from an already open file could result in an Exception.