Saltearse al contenido

Guía del lenguaje

lang.wlk

Class Exception

Base class for all Exceptions. Every exception and its subclasses

indicates conditions that a reasonable application might want to catch.

since 1.0

Estado
Atributo WollokDoc
const property message

specified detail message.

const property cause

specified cause

Comportamiento
Método WollokDoc
override native initialize()

Documentation not found

printStackTrace()

Prints this exception and its backtrace to the console

getStackTraceAsString()

Prints this exception and its backtrace as a string value

printStackTrace(printer)

private

Prints this exception and its backtrace to the specified printer

printStackTraceWithPrefix(prefix, printer)

private

createStackTraceElement(contextDescription, location)

private

native getFullStackTrace()

Provides programmatic access to the stack trace information

printed by printStackTrace() with full path files for linking

native getStackTrace()

Provides programmatic access to the stack trace information

printed by printStackTrace().

override ==(other)

Overrides the behavior to compare exceptions

Class StackOverflowException

Thrown when a stack overflow occurs because an application recurses too deeply.

since 1.5.1

Método WollokDoc

Class ElementNotFoundException

An exception that is thrown when a specified element cannot be found

Método WollokDoc

Class DomainException

An exception that is thrown for domain purpose

Estado
Atributo WollokDoc
const property source

Documentation not found

Comportamiento
Método WollokDoc

Class EvaluationError

(added by wollok-ts) An exception thrown whenever the interpreter fails to evaluate an expression

Método WollokDoc

Class MessageNotUnderstoodException

An exception that is thrown when an object cannot understand a certain message

Método WollokDoc

Class StackTraceElement

An element in a stack trace, represented by a context and a location

of a method where a message was sent

Estado
Atributo WollokDoc
const property contextDescription

Documentation not found

const property location

Documentation not found

Comportamiento
Método WollokDoc

Class Object

Representation of Wollok Object

Class Object is the root of the class hierarchy.

Every class has Object as a superclass.

since 1.0

Método WollokDoc
initialize()

Documentation not found

native identity()

Answers object identity of a Wollok object, represented by

a unique number in Wollok environment

native kindName()

Object description in english/spanish/... (depending on i18n configuration)

"2".kindName()  => Answers "a String"
2.kindName()    => Answers "a Integer"
<strong>private</strong>
native className()

Full name of Wollok object class

private

==(other)

Tells whether self object is "equal" to the given object

This method implements an equivalence relation on non-null object references:

- It is reflexive: for any non-null reference value x, x == x should return true.

- It is symmetric: for any non-null reference values x and y, x == y

should return true if and only if y == x returns true.

- It is transitive: for any non-null reference values x, y, and z,

if x == y returns true and y == z returns true,

then x == z should return true.

- It is consistent: for any non-null reference values x and y, multiple invocations

of x == y consistently return true or consistently return false,

provided no information used in equals comparisons on the objects is modified.

- For any non-null reference value x, x == null should return false.

The default behavior compares them in terms of identity (===)

!=(other)

Tells whether self object is not equal to the given one

===(other)

Documentation not found

!==(other)

Tells whether self object is not identical (the same) to the given one.

See === message.

equals(other)

Documentation not found

->(other)

Generates a Pair key-value association. see Pair.

toString()

String representation of Wollok object

shortDescription()

Shows a short, internal representation

printString()

Provides a visual representation of Wollok Object

By default, same as toString but can be overridden

like in String

messageNotUnderstood(messageName, parameters)

private

native generateDoesNotUnderstandMessage(target, messageName, parametersSize)

private

internal method: generates a does not understand message

parametersSize must be an integer value

error(aMessage)

Builds an exception with a message

native checkNotNull(value, message)

private

Singleton void

Representation for methods that only have side effects

Método WollokDoc

Class Pair

Representation of a Key/Value Association.

It is also useful if you want to model a Point.

Estado
Atributo WollokDoc
const property x

Documentation not found

const property y

Documentation not found

Comportamiento
Método WollokDoc
key()

Documentation not found

value()

Documentation not found

override ==(other)

Two pairs are equal if they have the same values

new Pair(x = 1, y = 2) == new Pair(x = 1, y = 2)  ==> Answers true
override toString()

String representation of a Pair

Class Collection

The root class in the collection hierarchy.

A collection represents a group of objects, known as its elements.

Método WollokDoc
max(closure)

Answers the element that is considered to be/have the maximum value.

The criteria is given by a closure that receives a single element

as input (one of the element). The closure must return a comparable

value (something that understands the >, >= messages).

If collection is empty, an ElementNotFound exception is thrown.

["a", "ab", "abc", "d" ].max({ e => e.length() })
=> Answers "abc"
[].max({ e => e.length() })
=> Throws error, list must not be empty
max()

Answers the element that represents the maximum value in the collection.

The criteria is by direct comparison of the elements (they must be sortable).

If collection is empty, an ElementNotFound exception is thrown.

[11, 1, 4, 8, 3, 15, 6].max() =>  Answers 15
[].max()                      =>  Throws error, list must not be empty
maxIfEmpty(toComparableClosure, emptyCaseClosure)

Answers the element that is considered to be/have the maximum value,

or applies a closure if the collection is empty.

The criteria is given by a closure that receives a single element

as input (one of the element). The closure must return a comparable

value (something that understands the >, >= messages).

The closure to execute when the collection is empty is given as a second

argument.

["a", "ab", "abc", "d" ].maxIfEmpty({ e => e.length() }, { "default" })
=> Answers "abc"
[].maxIfEmpty({ e => e.length() }, { "default" })
=> Answers "default"
maxIfEmpty(emptyCaseClosure)

Answers the element that is considered to be/have the maximum value,

or applies a closure if the collection is empty.

The criteria is by direct comparison of the elements.

The closure to execute when the collection is empty is given as a second

argument.

[11, 1, 4, 8, 3, 15, 6].maxIfEmpty({ 99 }) =>  Answers 15
[].maxIfEmpty({ 99 })                      =>  Answers 99
min(closure)

Answers the element that is considered to be/have the minimum value.

The criteria is given by a closure that receives a single element

as input (one of the element). The closure must return a comparable

value (something that understands the <, <= messages).

["ab", "abc", "hello", "wollok world"].min({ e => e.length() })
=>  Answers "ab"
[].min({ e => e.length() })
=> Throws error, list must not be empty
min()

Answers the element that represents the minimum value in the

non-empty collection.

The criteria is by direct comparison of the elements.

[11, 1, 4, 8, 3, 15, 6].min()  => Answers 1
[].min()                       => Throws error, list must not be empty
minIfEmpty(toComparableClosure, emptyCaseClosure)

Answers the element that is considered to be/have the minimum value,

or applies a closure if the collection is empty.

The criteria is given by a closure that receives a single element

as input (one of the element). The closure must return a comparable

value (something that understands the >, >= messages).

The closure to execute when the collection is empty is given as a second

argument.

["ab", "abc", "hello", "wollok world"].minIfEmpty({ e => e.length() }, { "default" })
=>  Answers "ab"
[].minIfEmpty({ e => e.length() }, { "default" })
=> Answers "default"
minIfEmpty(emptyCaseClosure)

Answers the element that is considered to be/have the minimum value,

or applies a closure if the collection is empty.

The criteria is by direct comparison of the elements.

The closure to execute when the collection is empty is given as a second

argument.

[11, 1, 4, 8, 3, 15, 6].minIfEmpty({ 99 })  => Answers 1
[].minIfEmpty({ 99 })                       => Answers 99
absolute(closure, criteria, emptyCaseClosure)

private

uniqueElement()

Answers the unique element in the collection.

If collection is empty, an error is thrown.

If collection has more than one element, an error is thrown.

[1].uniqueElement()    => Answers 1
[].uniqueElement()     => Throws error, list must not be empty
[1, 2].uniqueElement() => Throws error, list must have one element
+(elements)

Concatenates this collection to all elements from the given

collection parameter giving a new collection

(no side effect)

[1, 2] + [3]   => Answers [1, 2, 3]
[1, 2] + #{3}  => supports concatenation between lists and sets, answers [1, 2, 3]
#{} + []       => Answers #{}
addAll(elements)

Adds all elements from the given collection parameter to self collection.

This is a side effect operation.

const list = []
list.addAll(#{2, 4})  => list == [2, 4], always pointing to a list
removeAll(elements)

Removes all elements of the given collection parameter from self collection.

This is a side effect operation.

const list = [1, 6, 5]
list.removeAll([6]) => list == [1, 5]
removeAllSuchThat(closure)

Removes those elements that meet a given condition.

This is a side effect operation.

Supports empty collections.

const list = [1, 6, 5]
list.removeAllSuchThat { e => e.even() } => list == [1, 5]
isEmpty()

Tells whether self collection has no elements

[1, 6, 5].isEmpty() => Answers false
[].isEmpty()        => Answers true
validateNotEmpty(operation)

private

Throws error if self collection is empty

forEach(closure)

Performs an operation on every element of self collection.

The logic to execute is passed as a closure that takes a single parameter.

Supports empty collections.

returns nothing

plants.forEach { plant => plant.takeSomeWater() }
all(predicate)

Answers whether all the elements of self collection satisfy a given

condition. The condition is a closure argument that takes a single

element and answers a boolean value.

returns true/false

plants.all({ plant => plant.hasFlowers() })
[1, 3, 5].all { number => number.odd() }    => Answers true
[].all { number => number.odd() }           => Answers true
any(predicate)

Tells whether at least one element of self collection satisfies a

given condition. The condition is a closure argument that takes a

single element and answers a boolean value.

returns true/false

plants.any({ plant => plant.hasFlowers() })
[1, 2, 3].any { number => number.even() }   ==> Answers true
[].any { number => number.even() }          ==> Answers false
find(predicate)

Answers the element of self collection that satisfies a given condition.

If more than one element satisfies the condition then it depends

on the specific collection class which element will be returned.

returns the element that complies the condition

throws ElementNotFoundException if no element matched the given predicate

users.find { user => user.name() == "Cosme Fulanito" }
#{1, 4, 5}.find { number => number.even() }  => Answers 4
#{1, 3}.find { number => number.even() }     => Throws ElementNotFoundException
#{}.find { number => number.even() }         => Throws ElementNotFoundException
findOrDefault(predicate, value)

Answers the element of self collection that satisfies a given condition,

or the given default otherwise, if no element matched the predicate.

If more than one element satisfies the condition then it depends on the specific

collection class which element will be returned.

returns the element that complies the condition or the default value

users.findOrDefault({ user => user.name() == "Cosme Fulanito" }, homer)
[1, 3, 5].findOrDefault({ number => number.even() }, 0)  => Answers 0
[].findOrDefault({ number => number.even() }, 0)         => Answers 0
native findOrElse(predicate, continuation)

Answers the element of self collection that satisfies a given condition,

or the the result of evaluating the given continuation.

If more than one element satisfies the condition then it depends on the

specific collection class which element will be returned.

returns the element that complies the condition or the result

of evaluating the continuation

users.findOrElse({ user => user.name() == "Cosme Fulanito" }, { homer })
[1, 3, 5].findOrElse({ number => number.even() }, { 6.max(4) }) => Answers 6
[].findOrElse({ number => number.even() }, { false })           => Answers false
count(predicate)

Counts all elements of self collection that satisfies a given condition

The condition is a closure argument that takes a single element and

answers a number.

returns an integer number

plants.count { plant => plant.hasFlowers() }
#{1, 2, 3, 4, 5}.count { number => number.odd() }  => Answers 3
#{}.count { number => number.odd() }               => Answers 0
occurrencesOf(element)

Counts the occurrences of a given element in self collection.

returns an integer number

[1, 8, 4, 1].occurrencesOf(1)  => Answers 2
[].occurrencesOf(2)            => Answers 0
sum(closure)

Collects the sum of each value for all elements.

This is similar to call a map {} to transform each element into a

number object and then adding all those numbers.

The condition is a closure argument that takes a single element and

answers a boolean value.

returns an integer

const totalNumberOfFlowers = plants.sum{ plant => plant.numberOfFlowers() }
[].sum { employee => employee.salary() }   => Answers 0
sum()

Sums all elements in the collection.

returns a number

[1, 2, 3, 4, 5].sum()  => Answers 15
[].sum()               => Answers 0
map(closure)

Answers a new collection that contains the result of transforming

each of self collection's elements using a given closure.

The condition is a closure argument that takes a single element

and answers an object.

returns another list

const ages = users.map({ user => user.age() })
[1, 2, 3].map { number => number.odd() }  => Answers [true, false, true]
[].map { number => number.odd() }         => Answers []
flatMap(closure)

Flattens a collection of collections: Map + flatten operation

see map

see flatten

object klaus {
method languages() = ["c", "cobol", "pascal"]
}
object fritz {
method languages() = ["java", "perl"]
}
[klaus, fritz].flatMap({ person => person.languages() })
=> Answers ["c", "cobol", "pascal", "java", "perl"]
filter(closure)

Answers a new collection that contains the elements that

meet a given condition. The condition is a closure argument that

takes a single element and answers a boolean.

returns another collection (same type as self one)

const overageUsers = users.filter({ user => user.age() >= 18 })
#{1, 2, 3, 4, 5}.filter { number => number.even() }   => Answers #{2, 4}
[1, 2, 3].filter { number => number.even() }          => Answers [2]
#{}.filter { number => number.even() }                => Answers #{}
contains(element)

Answers whether this collection contains the specified element.

[].contains(3)        => Answers false
[1, 2, 3].contains(2) => Answers true
flatten()

Flattens a collection of collections

[ [1, 2], [3], [4, 0], [] ].flatten()
=> Answers [1, 2, 3, 4, 0]
override toString()

private

abstract toStringPrefix()

private

abstract toStringSuffix()

private

override printString()

Provides a (short) visual representation of this collection.

abstract asList()

Converts a collection to a list

abstract asSet()

Converts a collection to a set (removing duplicates if necessary)

[1, 2, 3].asSet()       => Answers #{1, 2, 3}
[].asSet()              => Answers #{}
[1, 2, 1, 1, 2].asSet() => Answers #{1, 2}
#{1, 2, 3}.asSet()      => Answers #{1, 2, 3}
#{}.asSet()             => Answers #{}
<strong>see</strong> Set
copy()

Answers a new collection of the same type and with the same content

as self. Supports empty collections.

returns a new collection

const usersCopy = users.copy()
copyWithout(elementToRemove)

Answers a new collection without element that is passed by parameter.

If the element occurs more than once in the collection, all occurrences

will be removed.

returns a new Collection

[1, 5, 9, 2, 4].copyWithout(9) => Answers [1, 5, 2, 4]
[1, 5, 9, 2, 9].copyWithout(9) => Answers [1, 5, 2]
copyWith(elementToAdd)

Answers a new collection with the added element which is received by parameter.

returns a new Collection

[1, 5, 9, 2, 4].copyWith(9) => Answers [1, 5, 2, 4, 9]
sortedBy(closure)

Answers a new List that contains the elements of self collection

sorted by a criteria given by a closure. The closure receives two objects

X and Y and answers a boolean, true if X should come before Y in the

resulting collection. Supports empty collections.

returns a new List

const usersByAge = users.sortedBy({ a, b => a.age() < b.age() })
const studentsByNameDesc = students.sortedBy({ a, b => a.name() > b.name() })
[1, 5, 9, 2, 4].sortedBy { a, b => a < b } => Answers [1, 2, 4, 5, 9]
[1, 5, 9, 2, 4].sortedBy { a, b => a > b } => Answers [9, 5, 4, 2, 1]
[].sortedBy { a, b => a > b }              => Answers []
abstract newInstance()

Answers a new, empty collection of the same type as self.

returns a new collection

const newCollection = users.newInstance()
anyOne()

see subclasses implementations

add(element)

see subclasses implementations

remove(element)

see subclasses implementations

fold(element, closure)

see subclasses implementations

size()

see subclasses implementations

abstract clear()

Removes all of the elements from this set. This is a side effect operation.

see subclasses implementations

join(separator)

Answers the concatenated string representation of the elements in the given set.

You can pass an optional character as an element separator (default is ",")

["hola", "como", "estas"].join(" ") ==> Answers "hola como estas"
join()

Answers the concatenated string representation of the elements in the given set

with default element separator (",")

["hola", "como", "estas"].join()    ==> Answers "hola,como,estas"

Singleton collection

Builder object for collections.

It compensates for the lack of vararg constructors.

Método WollokDoc
list(elements)

Documentation not found

set(elements)

Documentation not found

Class Set

A collection that contains no duplicate elements.

It models the mathematical set abstraction.

A Set guarantees no order of elements.

Note: Great care must be exercised if mutable objects are used as set elements.

The behavior of a set is not specified if the value of an object is changed in

a manner that affects equals comparisons while the object is an element in the set.

A special case of this prohibition is that it is not permissible for a set to contain

itself as an element.

since 1.3

Método WollokDoc
override newInstance()

Documentation not found

override toStringPrefix()

private

override toStringSuffix()

private

override asList()

Converts this set to a list.

#{1, 2, 3}.asList() => Answers [1, 2, 3]
#{}.asList()        => Answers []
<strong>see</strong> List
override asSet()

Converts a collection to a set (removing duplicates if necessary)

[1, 2, 3].asSet()       => Answers #{1, 2, 3}
[].asSet()              => Answers #{}
[1, 2, 1, 1, 2].asSet() => Answers #{1, 2}
#{1, 2, 3}.asSet()      => Answers #{1, 2, 3}
#{}.asSet()             => Answers #{}
<strong>see</strong> Set
override native anyOne()

Answers any element of a non-empty collection

#{1, 2, 3}.anyOne() => Answers 1, for example
#{}.anyOne()        => Throws error, set must not be empty
union(another)

Answers a new Set with the elements of both self and another collection.

#{1, 2}.union(#{5, 2})   => #{1, 2, 5}
#{}.union(#{3})          => #{3}
<strong>returns</strong> a Set
intersection(another)

Answers a new Set with the elements of self that exist in another collection

#{1, 2}.intersection(#{5, 2})   => #{2}
#{}.intersection(#{3})          => #{}
<strong>returns</strong> a Set
difference(another)

Answers a new Set with the elements of self that don't exist in another collection

#{1, 2}.difference(#{5, 2}) => #{1}
#{3}.difference(#{})        => #{3}
<strong>returns</strong> a Set
override native fold(initialValue, closure)

Reduce a collection to a certain value, beginning with a seed or initial value.

#{1, 9, 3, 8}.fold(0, {acum, each => acum + each})
=> Answers 21, the sum of all elements
#{}.fold(0, {acum, each => acum + each})
=> Answers 0, the seed.
var numbers = #{3, 2, 9, 1, 7}
numbers.fold(numbers.anyOne(), { acum, number => acum.max(number) })
=> Answers 9, the maximum of all elements
override native filter(closure)

Answers a new set with the elements meeting

a given condition. The condition is a closure argument that

takes a single element and answers a boolean.

#{1, 2, 3, 4, 5}.filter { number => number.even() }   => Answers #{2, 4}
#{}.filter { number => number.even() }                => Answers #{}
<strong>see</strong> Collection#filter(closure)
override native max()

Answers the element that represents the maximum value in the collection.

The criteria is by direct comparison of the elements.

If set is empty, an ElementNotFound exception is thrown.

#{1, 9, 3, 15}.max()  =>  Answers 15
#{}.max()             =>  Throws error, set must not be empty
<strong>see</strong> Collection#max()
override native findOrElse(predicate, continuation)

Tries to find an element in a collection (based on a closure) or

applies a continuation closure.

#{1, 9, 3, 8}.findOrElse({ n => n.even() }, { 100 })  => Answers  8
#{1, 5, 3, 7}.findOrElse({ n => n.even() }, { 100 })  => Answers  100
override native add(element)

Adds the specified element to this set if it is not already present.

const set = #{}
set.add(3)   => set = #{3}
set.add(2)   => set = #{2, 3}
set.add(2)   => set = #{2, 3}, second add produces no effect
native unsafeAdd(element)

private

override native remove(element)

Removes the specified element from this set if it is present.

const set = #{2, 3}
set.remove(3) => set = #{2}
set.remove(4) => set = #{2}, remove operation produces no effect
override native size()

Answers the number of elements in this set (its cardinality).

#{2, 3}.size()   => Answers 2
#{}.size()       => Answers 0
override native clear()

Removes all of the elements from this set. This is a side effect operation.

const set = #{2, 3}
set.clear()         => set = #{}
override native join(separator)

Answers the concatenated string representation of the elements in the given set.

You can pass an optional character as an element separator (default is ",")

#{1, 5, 3, 7}.join(":")                   => Answers "1:5:3:7"
#{"you","will","love","wollok"}.join(" ") => Answers "love will wollok you"
#{}.join(",")                             => Answers ""
override native join()

Answers the concatenated string representation of the elements in the given set

with default element separator (",")

#{"you","will","love","wollok"}.join()    => Answers "love,will,wollok,you"
override native contains(other)

Answers whether this collection contains the specified element.

#{}.contains(3)        => Answers false
#{1, 2, 3}.contains(2) => Answers true
#{1, 2, 3}.contains(4) => Answers false
<strong>see</strong> List#contains(other)
override native ==(other)

Two sets are equals if they have the same elements, no matter

the order.

#{} == #{}         => Answers true
#{1, 2} == #{2, 1} => Answers true
#{3, 2} == #{2, 1} => Answers false

Class List

An ordered collection (also known as a sequence).

You iterate the list the same order elements are inserted.

The user can access elements by their integer index (position in the list).

A List can contain duplicate elements.

since 1.3

Método WollokDoc
native get(index)

Documentation not found

override newInstance()

Creates a new list

override anyOne()

Answers any element of a non-empty collection.

#[1, 2, 3].anyOne() => Answers 3, for example
#[].anyOne()        => Throws error, list must not be empty
first()

Answers first element of the non-empty list

returns first element

[1, 2, 3, 4].first()  => Answers 1
[].first()            => Throws error, list must not be empty
head()

Synonym for first method

last()

Answers the last element of the non-empty list.

returns last element

[1, 2, 3, 4].last()  => Answers 4
[].last()            => Throws error, list must not be empty
override toStringPrefix()

private

override toStringSuffix()

private

override asList()

Converts this collection to a list. No effect on Lists.

see List

override asSet()

Converts a collection to a set (removing duplicates if necessary)

[1, 2, 3].asSet()       => Answers #{1, 2, 3}
[].asSet()              => Answers #{}
[1, 2, 1, 1, 2].asSet() => Answers #{1, 2}
#{1, 2, 3}.asSet()      => Answers #{1, 2, 3}
#{}.asSet()             => Answers #{}
<strong>see</strong> Set
subList(start)

Answers a view of the portion of this list between the specified start index

and the end of the list. Remember first element is position 0,

second is position 1, and so on.

If toIndex exceeds length of list, no error is thrown.

[1, 5, 3, 2, 7, 9].subList(2) => Answers [3, 2, 7, 9]
[1, 5, 3, 2, 7, 9].subList(4) => Answers [7, 9]
[].subList(1)                 => Answers []
subList(start, end)

Answers a view of the portion of this list between the specified fromIndex

and toIndex, both inclusive. Remember first element is position 0,

second is position 1, and so on.

If toIndex exceeds length of list, no error is thrown.

[1, 5, 3, 2, 7, 9].subList(2, 3) => Answers [3, 2]
[1, 5, 3, 2, 7, 9].subList(4, 6) => Answers [7, 9]
[].subList(1, 2)                 => Answers []
native sortBy(closure)

Sorts elements of a list by a specific closure.

Order of elements is modified (produces effect).

const list = [2, 9, 3]
list.sortBy { el1, el2 => el1 > el2 }
list.get(0)            => Answers 9
<strong>see</strong> List#sortedBy
take(n)

Takes first n elements of a list.

[1,9,2,3].take(5)  ==> Answers [1, 9, 2, 3]
[1,9,2,3].take(2)  ==> Answers [1, 9]
[1,9,2,3].take(-2) ==> Answers []
[].take(2)         ==> Answers []
drop(n)

Answers a new list dropping first n elements of a list.

This operation has no side effect.

[1, 9, 2, 3].drop(3)  ==> Answers [3]
[1, 9, 2, 3].drop(1)  ==> Answers [9, 2, 3]
[1, 9, 2, 3].drop(-2) ==> Answers [1, 9, 2, 3]
[].drop(2)            ==> Answers []
reverse()

Answers a new list reversing the elements,

so that first element becomes last element of the new list and so on.

This operation has no side effect.

[1, 9, 2, 3].reverse()  ==> Answers [3, 2, 9, 1]
[1, 2].reverse()        ==> Answers [2, 1]
[].reverse()            ==> Answers []
override native filter(closure)

Answers a new list with the elements meeting

a given condition. The condition is a closure argument that

takes a single element and answers a boolean.

[1, 2, 3, 4, 5].filter { number => number.even() }   => Answers [2, 4]
[].filter { number => number.even() }                => Answers []
<strong>see</strong> Collection#filter(closure)
override native contains(obj)

Answers whether this collection contains the specified element.

[].contains(3)        => Answers false
[1, 2, 3].contains(2) => Answers true
[1, 2, 3].contains(4) => Answers false
<strong>see</strong> Collection#contains(obj)
override native max()

Answers the element that represents the maximum value in the collection.

The criteria is by direct comparison of the elements (they must be sortable).

If collection is empty, an ElementNotFound exception is thrown.

[11, 1, 4, 8, 3, 15, 6].max() =>  Answers 15
[].max()                      =>  Throws error, list must not be empty
<strong>see</strong> Collection#max()
override native fold(initialValue, closure)

Reduce a collection to a certain value, beginning with a seed or initial value

[1, 9, 3, 8].fold(0, {acum, each => acum + each})
=> Answers 21, the sum of all elements
[].fold(0, {acum, each => acum + each})
=> Answers 0, the seed.
const numbers = [3, 2, 9, 1, 7]
numbers.fold(numbers.anyOne(), { acum, number => acum.max(number) })
=> Answers 9, the maximum of all elements
override native findOrElse(predicate, continuation)

Finds the first element matching the boolean closure,

or evaluates the continuation block closure if no element is found

[1, 9, 3, 8].findOrElse({ n => n.even() }, { 100 })  => Answers  8
[1, 5, 3, 7].findOrElse({ n => n.even() }, { 100 })  => Answers  100
override native add(element)

Adds the specified element as last one

const list = []
list.add(3)   => list = [3]
list.add(2)   => list = [3, 2]
list.add(2)   => list = [3, 2, 2]
override native remove(element)

Removes an element in this list, if it is present.

const list = [2, 3]
list.remove(3) => list = [2]
list.remove(4) => list = [2], remove operation produces no effect
override native size()

Answers the number of elements

[2, 3].size()   => Answers 2
[].size()       => Answers 0
override native clear()

Removes all of the mappings from this Dictionary.

This is a side effect operation.

const list = [2, 3]
list.clear()     => list = []
override native join(separator)

Answers the concatenated string representation of the elements in the given set.

You can pass an optional character as an element separator (default is ",")

[1, 5, 3, 7].join(":") => Answers "1:5:3:7"
["you","will","love","wollok"].join(" ") => Answers "you will love wollok"
override native join()

Answers the concatenated string representation of the elements in the given set,

using default element separator (",")

["you","will","love","wollok"].join()    => Answers "you,will,love,wollok"
override native ==(other)

A list is == another list if all elements are equal (defined by == message)

[] == []         => Answers true
[1, 2] == [2, 1] => Answers false
[1, 2] == [1, 2] => Answers true
native withoutDuplicates()

Answers the list without duplicate elements. Preserves order of elements.

[1, 3, 1, 5, 1, 3, 2, 5].withoutDuplicates() => Answers [1, 3, 5, 2]

[].withoutDuplicates() => Answers []

randomize()

Shuffles the order of the elements in the list.

This is a side effect operation.

const list = [1, 2 ,3]
list.randomize()     => list = [2, 1, 3]
randomized()

Answers a new list of the same type and with the same content in a random order

[1, 2, 3, 4].randomized() => Answers [2, 3, 1, 4]
[1, 2, 3, 4].randomized() => Answers [2, 1 ,4 ,3]

Class Dictionary

Represents a set of key -> values

Método WollokDoc
override native initialize()

Documentation not found

native put(_key, _value)

Adds or updates a value based on a key.

If key is not present, a new value is added.

If key is present, value is updated.

This is a side effect operation.

const phones = new Dictionary()
phones.put("4004-4004", rolo)
=> phones == a Dictionary ["4004-4004" -> rolo]
native basicGet(_key)

Answers the value to which the specified key is mapped,

or null if this Dictionary contains no mapping for the key.

phones.basicGet("4004-4004")  => Answers rolo
phones.basicGet("4004-4005")  => Answers null
getOrElse(_key, _closure)

Answers the value to which the specified key is mapped,

or evaluates a non-parameter closure otherwise.

phones.getOrElse("4004-4004", { 0 })  => Answers rolo
phones.getOrElse("4004-4005", { 0 })  => Answers 0
get(_key)

Answers the value to which the specified key is mapped.

If this Dictionary contains no mapping for the key, an error is thrown.

phones.get("4004-4004")  => Answers rolo
phones.get("4004-4005")  => Throws ElementNotFoundException
size()

Answers the number of key-value mappings in this Dictionary.

phones.size()           => Answers 1
new Dictionary().size() => Answers 0
isEmpty()

Answers whether the dictionary has no elements

phones.isEmpty()           => Answers false
new Dictionary().isEmpty() => Answers true
containsKey(_key)

Answers whether this Dictionary contains a mapping for the specified key.

phones.containsKey("4004-4004")  => Answers true
phones.containsKey("4004-4005")  => Answers false
new Dictionary().containsKey(1)  => Answers false
containsValue(_value)

Answers whether if this Dictionary maps one or more keys to the specified value.

const numbers = new Dictionary()
numbers.put("one", 1)
numbers.put("two", 2)
numbers.containsValue(2)          => Answers true
numbers.containsValue(5)          => Answers false
new Dictionary().containsValue(3) => Answers false
native remove(_key)

Removes the mapping for a key from this Dictionary if it is present.

If key is not present nothing happens.

This is a side effect operation.

const numbers = new Dictionary()
numbers.put("one", 1)
numbers.put("two", 2)
numbers.remove("one")   => numbers is a dictionary ("two" -> 2)
numbers.remove("three") => nothing happens
native keys()

Answers a list of the keys contained in this Dictionary.

const numbers = new Dictionary()
numbers.put("one", 1)
numbers.put("two", 2)
numbers.keys()   => ["one", "two"]
native values()

Answers a list of the values contained in this Dictionary.

const numbers = new Dictionary()
numbers.put("one", 1)
numbers.put("two", 2)
numbers.values()   => [1, 2]
native forEach(closure)

Performs the given action for each entry in this Dictionary

until all entries have been processed or the action throws an exception.

Expected closure with two parameters: the first associated with key and

second with value.

mapaTelefonos.forEach({ k, v => result += k.size() + v.size() })
native clear()

Removes all of the mappings from this Dictionary.

This is a side effect operation.

const numbers = new Dictionary()
numbers.put("one", 1)
numbers.put("two", 2)
numbers.clear()  => phones == empty dictionary
override toString()

String representation of a Dictionary

const numbers = new Dictionary()
numbers.put("one", 1)
numbers.put("two", 2)
=> Answers a Dictionary ["one" -> 1, "two" -> 2]
override ==(other)

Two dictionaries are equal if they have the same keys and values

Class Number

In Wollok we have numbers as an immutable representation. You can customize

how many decimals you want to work with, and printing strategies. So

number two could be printed as "2", "2,00000", "2,000", etc.

Coercing strategy for numbers can be

1) rounding up: 2,3258 using 3 decimals will result in 2,326

2) rounding down or truncation: 2,3258 using 3 decimals will

result in 2,325

3) not allowed: 2,3258 using 3 decimals will throw an exception

since decimals exceeds maximum allowed

(unification between Double and Integer in a single Number class)

since 1.3

noInstantiate

Método WollokDoc
native coerceToInteger()

private

Applies coercing strategy to integer. If it is an integer, nothing happens.

Otherwise, if it is a decimal, defined coercing algorithm is applied

(see definition of class Number)

native coerceToPositiveInteger()

private

see coerceToInteger

Applies coercing strategy to integer. And throws exception if it is negative.

override native ===(other)

Two references are identical if they are the same number

native +(other)

Documentation not found

native -(other)

Documentation not found

native *(other)

Documentation not found

native /(other)

Documentation not found

div(other)

Integer division between self and other

8.div(3)      ==> Answers 2
15.div(5)     ==> Answers 3
8.2.div(3.3)  ==> Answers 2
native **(other)

raisedTo operation

3.2  2 ==> Answers 10.24
3  2   ==> Answers 9
native %(other)

Answers remainder of division between self and other

override native toString()

String representation of self number

..(end)

Builds a Range between self and end

1..4       Answers ==> a new Range object from 1 to 4
native >(other)

Documentation not found

native <(other)

Documentation not found

>=(other)

Documentation not found

<=(other)

Documentation not found

native abs()

Answers absolute value of self

2.abs()      ==> 2
(-3).abs()   ==> 3 (be careful with parentheses)
2.7.abs()    ==> Answers 2.7
(-3.2).abs() ==> Answers 3.2 (be careful with parentheses)
native invert()

Inverts sign of self

3.invert()      ==> Answers -3
(-2).invert()   ==> Answers 2 (be careful with parentheses)
3.2.invert()    ==> -3.2
(-2.4).invert() ==> 2.4 (be careful with parentheses)
max(other)

Answers the greater number between two

5.max(8)    ==> Answers 8
min(other)

Answers the lower number between two. see max

5.min(8)    ==> Answers 5
limitBetween(limitA, limitB)

Given self and a range of integer values,

answers self if it is in that range

or nearest value from self to that range

4.limitBetween(2, 10) ==> Answers 4, because 4 is in the range
4.limitBetween(6, 10) ==> Answers 6, because 4 is not in range 6..10, and 6 is nearest value to 4
4.limitBetween(1, 2)  ==> Answers 2, because 4 is not in range 1..2, but 2 is nearest value to 4
between(min, max)

Answers whether self is between min and max

2.between(2, 3) ==> Answers true
6.between(4, 6) ==> Answers true
3.between(4, 6) ==> Answers false
squareRoot()

Documentation not found

square()

Answers square of self

3.square() => Answers 9
even()

Answers whether self is an even number

(divisible by 2, mathematically 2k).

Self must be an integer value

odd()

Answers whether self is an odd number

(not divisible by 2, mathematically 2k + 1).

Self must be an integer value

rem(other)

Answers remainder between self and other

5.rem(3)   ==> Answers 2
5.5.rem(3) ==> Answers 2
stringValue()

Self as String value. Equivalent: toString()

native roundUp(_decimals)

Rounds up self up to a certain amount of decimals.

Amount of decimals must be a positive and integer value.

1.223445.roundUp(3)  ==> 1.224
-1.223445.roundUp(3) ==> -1.224
14.6165.roundUp(3)   ==> 14.617
5.roundUp(3)         ==> 5
native truncate(_decimals)

Truncates self up to a certain amount of decimals.

Amount of decimals must be a positive and integer value.

1.223445.truncate(3) ==> 1.223
14.6165.truncate(3)  ==> 14.616
-14.6165.truncate(3) ==> -14.616
5.truncate(3)        ==> 5
native randomUpTo(max)

Answers a random number between self and max

roundUp()

Answers the next integer greater than self

13.224.roundUp()  ==> 14
-13.224.roundUp() ==> -14
15.942.roundUp()  ==> 16
native round()

Returns the value of a number rounded to the nearest integer.

native gcd(other)

greater common divisor.

Both self and "other" parameter are coerced to be integer values.

8.gcd(12) ==> Answers 4
5.gcd(10) ==> Answers 5
lcm(other)

least common multiple.

Both self and "other" parameter are coerced to be integer values.

3.lcm(4)  ==> Answers 12
6.lcm(12) ==> Answers 12
digits()

Number of digits of self (without sign)

600.digits()     ==> Answers 3
6.00012.digits() ==> Answers 6
-100.digits()    ==> Answers -3
native isInteger()

Tells if this number can be considered an integer number.

2.isInteger()     ==> Answers true
(2.0).isInteger() ==> Answers true
(2.3).isInteger() ==> Answers false
This could depend also on the rounding strategy, for example:
(2.0001).isInteger() ==> Answers false if rounding strategy is set to 5 decimal places (default)
(2.0001).isInteger() ==> Answers true if rounding strategy is set to 3 decimal places
isPrime()

Answers whether self is a prime number,

like 2, 3, 5, 7, 11 ...

Self must be an integer positive value

times(action)

Executes the given action n times (n = self)

Self must be a positive integer value.

The closure must have one argument (index goes from 1 to self)

4.times({ i => console.println(i) }) ==> Answers
1
2
3
4
plus()

Allows users to define a positive number with 1 or +1

Class String

Strings are constant;

their values cannot be changed after they are created.

noInstantiate

Método WollokDoc
native length()

Answers the number of elements

charAt(index)

Answers the char value at the specified index. An index ranges

from 0 to length() - 1. The first char value of the sequence is

at index 0, the next at index 1, and so on, as for array indexing.

Parameter index must be a positive integer value.

+(other)

Concatenates the specified string to the end of this string.

"cares" + "s" => Answers "caress"
native concat(other)

Concatenates the specified string to the end of this string. Same as +.

"cares".concat("s") => Answers "caress"
native startsWith(prefix)

Tests if this string starts with the specified prefix.

It is case sensitive.

"mother".startsWith("moth")  ==> Answers true
"mother".startsWith("Moth")  ==> Answers false
native endsWith(suffix)

Tests if this string ends with the specified suffix.

It is case sensitive.

see startsWith

native indexOf(other)

Answers the index within this string of the first occurrence

of the specified character.

If character is not present, Answers -1

"pototo".indexOf("o")         ==> Answers 1
"unpredictable".indexOf("o")  ==> Answers -1
native lastIndexOf(other)

Answers the index within this string of the last

occurrence of the specified character.

If character is not present, Answers -1

"pototo".lastIndexOf("o")         ==> Answers 5
"unpredictable".lastIndexOf("o")  ==> Answers -1
native toLowerCase()

Converts all of the characters in this String to lower case

"Fer".toLowerCase()  ==> Answers "fer"
"".toLowerCase()     ==> Answers ""
native toUpperCase()

Converts all of the characters in this String to upper case

"Fer".toUpperCase()  ==> Answers "FER"
"".toUpperCase()     ==> Answers ""
native trim()

Answers a string whose value is this string,

with any leading and trailing whitespace removed.

"   emptySpace  ".trim()  ==> "emptySpace"
native reverse()

Answers a string reversing this string,

so that first character becomes last character of the new string and so on.

"hola".reverse()  ==> "aloh"
takeLeft(length)

see take

"word".takeLeft(3)  ==> Answers "wor"
"word".takeLeft(0)  ==> Answers ""
"word".takeLeft(-1) ==> Throws error
"".takeLeft(2)      ==> Answers ""
takeRight(_length)

Takes last n characters of this string.

n must be zero-positive integer.

"word".takeRight(3)  ==> Answers "ord"
"word".takeRight(0)  ==> Answers ""
"word".takeRight(-1) ==> Throws error
"".takeRight(2)      ==> Answers ""
native <(aString)

Documentation not found

<=(aString)

Documentation not found

native >(aString)

Documentation not found

>=(aString)

Documentation not found

native contains(element)

Answers whether this string contains the specified sequence of char values.

It is a case sensitive test.

"unusual".contains("usual")  ==> Answers true
"become".contains("CO")      ==> Answers false
isEmpty()

Answers whether this string has no characters

equalsIgnoreCase(aString)

Compares this String to another String, ignoring case considerations.

"WoRD".equalsIgnoreCase("Word")  ==> Answers true
native substring(index)

Answers a substring of this string beginning from

an inclusive index. Parameter index must be a positive

integer value.

"substitute".substring(6)  ==> Answers "tute", second "t" is in position 6
"effect".substring(0)      ==> Answers "effect", has no effect at all
native substring(startIndex, endIndex)

Answers a substring of this string beginning

from an inclusive index up to another inclusive index

"walking".substring(2, 4)   ==> Answers "lk"
"walking".substring(3, 5)   ==> Answers "ki"
"walking".substring(0, 5)   ==> Answers "walki"
"walking".substring(0, 45)  ==> throws an out of range exception
split(expression)

Splits this string around matches of the given string.

Answers a list of strings.

"this,could,be,a,list".split(",")
==> Answers ["this", "could", "be", "a", "list"]
"Esto Es una prueba".split(" ")
==> Answers ["Esto", "Es", "una", "prueba"]
"Esto Es una".split("")
==> Answers ["E","s","t","o"," ","E","s"," ","u","n","a"] , splitting into a character list
"Esto Es una".split("|")
==> Answers ["Esto Es una"], the same original string
"texto de prueba".split("texto de prueba")
==> Answers ["",""]
"a,b,,c,".split(",")
==> Answers ["a", "b", "", "c", ""]
"texto de prueba".split("de")
==> Answers ["texto ", " prueba"]
"aaaa".split("aa")
==> Answers ["", "", ""]
native replace(expression, replacement)

Answers a string resulting from replacing all occurrences of

expression in this string with replacement

"stupid is what stupid does".replace("stupid", "genius")
==> Answers "genius is what genius does"
override native toString()

This object (which is already a string!) is itself returned

override printString()

String implementation of printString,

simply adds quotation marks

override native ==(other)

Compares this string to the specified object.

The result is true if and only if the

argument is not null and is a String object

that represents the same sequence of characters as this object.

size()

A synonym for length

take(n)

Takes first n characters of this string.

n must be zero-positive integer.

"lowercase".take(3)  ==> Answers "low"
"lowercase".take(0)  ==> Answers ""
"lowercase".take(-1) ==> Throws error
"".take(2)           ==> Answers ""
drop(n)

Answers a new string dropping

first n characters of this string.

n must be zero-positive integer.

"caption".drop(4)    ==> Answers "ion"
"caption".drop(0)    ==> Answers "caption"
"caption".drop(-1)   ==> Throws error
"".drop(2)           ==> Answers ""
words()

Splits this strings into several words.

"how does words work?".words()
==> Answers ["how", "does", "words", "work?"]
"".words() ==> Answers []
capitalize()

Changes the first letter of every word to

upper case in this string.

"javier fernandes".capitalize() ==> Answers "Javier Fernandes"

Class Boolean

Represents a Boolean value (true or false)

noInstantiate

Método WollokDoc
native and(other)

Answers the result of applying the logical AND operator

to the specified boolean operands self and other

native &&(other)

A synonym for and operation

native or(other)

Answers the result of applying the logical OR operator

to the specified boolean operands self and other

native ||(other)

A synonym for or operation

override native toString()

String representation of this boolean value.

override native ==(other)

Compares this string to the specified object.

The result is true if and only if the

argument is not null and represents same value

(true or false)

native negate()

NOT logical operation

Class Range

Represents a finite arithmetic progression

of integer numbers with optional step

If start = 1, end = 8, Range will represent [1, 2, 3, 4, 5, 6, 7, 8]

If start = 1, end = 8, step = 3, Range will represent [1, 4, 7]

since 1.3

Estado
Atributo WollokDoc
start

Documentation not found

end

Documentation not found

property step

Documentation not found

Comportamiento
Método WollokDoc
override initialize()

Instantiates a Range.

Both start and end must be integer values.

start()

Getter for start attribute

end()

Getter for end attribute

step(_step)

Setter for step attribute.

native forEach(closure)

Iterates over a Range from start to end, based on step.

new Range(start = 1, end = 3).forEach { value => console.println(value) }
=> prints 1, 2, 3
map(closure)

Answers a new collection that contains the result of

transforming each of self collection's elements using

a given closure.

The condition is a closure argument that takes an integer

and answers an object.

returns another list

(1..10).map({ n => n  2}) ==> Answers [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
flatMap(closure)

Map + flatten operation

see map

see flatten

(1..4).flatMap({ n => 1 .. n }) ==> Answers [1, 1, 2, 1, 2, 3, 1, 2, 3, 4]
asList()

private

isEmpty()

Answers whether this range contains no elements

see Collection#isEmpty()

fold(seed, foldClosure)

Reduce a range to a certain value, beginning with a seed or initial value.

(1..5).fold(0, {acum, each => acum + each})
=> Answers 15, the sum of all elements
<strong>see</strong> List#fold(seed, foldClosure)
size()

Answers the number of elements

new Range(start = 0, end = 2).size()  ==> Answers 3
new Range(start = -2, end = 2).size() ==> Answers 5
any(closure)

Tells whether at least one element of range satisfies a

given condition. The condition is a closure argument that takes a

number and answers a boolean value.

returns true/false

(1..5).any { number => number.even() }   ==> Answers true
<strong>see</strong> List#any(closure)
all(closure)

Answers whether all the elements of range satisfy a given

condition. The condition is a closure argument that takes a number

and answers a boolean value.

returns true/false

(1..5).all { number => number.odd() }    => Answers false
<strong>see</strong> List#all(closure)
filter(closure)

Answers a new list with the elements meeting

a given condition. The condition is a closure argument that

takes a single element and answers a boolean.

(1..4).filter({ number => number.even() })   => Answers [2, 4]
<strong>see</strong> List#filter(closure)
min()

Answers the element that represents the minimum value in the range.

The criteria is by direct comparison of the elements (they must be sortable).

(1..5).min()  => Answers 1
<strong>see</strong> List#min()
max()

Answers the element that represents the maximum value in the range.

(1..15).max()                       =>  Answers 15
new Range(start = 2, end = 5).max() => Answers 5
<strong>see</strong> List#max()
native anyOne()

Answers a random integer contained in the range

new Range(start = 1, end = 3).anyOne() ==> Answers 1 or 2 or 3
contains(element)

Tests whether a number is contained in the range

new Range(start = 2, end = 5).contains(4) ==> Answers true
(new Range(start = 2, end = 5)).contains(0) ==> Answers false
sum()

Sums all elements in the collection.

returns a number

(1..5).sum()  => Answers 15
<strong>see</strong> List#sum()
sum(closure)

Sums all elements that match the boolean closure

(1..9).sum({ i => if (i.even()) i else 0 }) ==> Answers 20
count(closure)

Counts how many elements match the boolean closure

(1..9).count({ i => i.even() }) ==> Answers 4 (2, 4, 6 and 8 are even)
find(closure)

Answers the number of the range that satisfies a given condition.

throws ElementNotFoundException if no element matched the given predicate

(1..5).find { number => number.even() }   ==> Answers 2
<strong>see</strong> List#find(closure)
findOrElse(closure, continuation)

Finds the first number matching the boolean closure,

or evaluates the continuation block closure if no element is found

(1..5).findOrElse({ number => number < 0 }, { 100 })     => Answers 100
(1..5).findOrElse({ number => number.even() }, { 100 })  => Answers 2
<strong>see</strong> List#findOrElse(predicate, continuation)
findOrDefault(predicate, value)

Answers the number of the range that satisfies a given condition,

or the given default otherwise, if no element matched the predicate.

(1..5).findOrDefault({ number => number.even() }, 0) => Answers 2
(1..5).findOrDefault({ number => number < 0 }, 0)    => Answers 0
<strong>see</strong> List#findOrDefault(predicate, value)
sortedBy(closure)

Answers a new List that contains the elements of self collection

sorted by a criteria given by a closure. The closure receives two objects

X and Y and answers a boolean, true if X should come before Y in the

resulting collection.

returns a new List

(1..5).sortedBy { a, b => a > b } => Answers [5, 4, 3, 2, 1]
<strong>see</strong> List#sortBy
override toString()

String representation of this range object

Class Closure

Represents an executable piece of code. You can create a closure,

assign it to a reference, evaluate it many times,

send it as parameter to another object, and many useful things.

since 1.3

noInstantiate

Método WollokDoc
native apply(parameters)

Evaluates this closure passing its parameters

{ number => number + 1 }.apply(8) ==> Answers 9 // 1 parameter
{ "screw" + "driver" }.apply()    ==> Answers "screwdriver" // no parameter
override native toString()

String representation of this closure object

Singleton calendar

Utility object to contain Date and Date-related info, such as WKO and factory methods.

since 3.0.0

Estado
Atributo WollokDoc
const property monday

Documentation not found

const property tuesday

Documentation not found

const property wednesday

Documentation not found

const property thursday

Documentation not found

const property friday

Documentation not found

const property saturday

Documentation not found

const property sunday

Documentation not found

const property daysOfWeek

Documentation not found

Comportamiento
Método WollokDoc
native today()

Documentation not found

yesterday()

Documentation not found

tomorrow()

Documentation not found

Class Date

Represents a Date (without time). A Date is immutable, once created you can not change it.

since 1.4.5

Estado
Atributo WollokDoc
const property day

Documentation not found

const property month

Documentation not found

const property year

Documentation not found

Comportamiento
Método WollokDoc
override toString()

String representation of a date

override native ==(_aDate)

Two dates are equals if they represent the same date

native plusDays(_days)

Answers a copy of this Date with the specified number of days added.

Parameter must be an integer value.

This operation has no side effect (a new date is returned).

new Date(day = 12, month = 5, year = 2018).plusDays(1)
==> Answers 13/5/2018, a day forward
new Date(day = 12, month = 5, year = 2018).plusDays(-1)
==> Answers 11/5/2018, a day back
native plusMonths(_months)

Answers a copy of this Date with the specified number of months added.

Parameter must be an integer value.

This operation has no side effect (a new date is returned).

new Date(day = 31, month = 1, year = 2018).plusMonths(1)
==> Answers 28/2/2018, a month forward
new Date(day = 12, month = 5, year = 2018).plusMonths(-1)
==> Answers 12/4/2018, a month back
native plusYears(_years)

Answers a copy of this Date with the specified number of years added.

Parameter must be an integer value.

This operation has no side effect (a new date is returned).

new Date(day = 31, month = 1, year = 2018).plusYears(1)
==> Answers 31/1/2019, a year forward
new Date(day = 12, month = 5, year = 2018).plusYears(-1)
==> Answers 12/5/2017, a year back
native isLeapYear()

Checks if the year is a leap year, like 2000, 2004, 2008...

new Date(day = 12, month = 5, year = 2018).isLeapYear() ==> Answers false
dayOfWeek()

Answers the day of the week of the Date with an object representation.

There is a wko (well known object) for every day of the week.

new Date(day = 24, month = 2, year = 2018).dayOfWeek() ==> Answers saturday object
native internalDayOfWeek()

Answers the day of week of the Date, where

1 = MONDAY

2 = TUESDAY

3 = WEDNESDAY

...

7 = SUNDAY

new Date(day = 24, month = 2, year = 2018).internalDayOfWeek() ==> Answers 6 (SATURDAY)
native -(_aDate)

Answers the difference in days between two dates, assuming self is minuend and _aDate is subtrahend.

new Date().plusDays(4) - new Date() ==> Answers 4
new Date() - new Date().plusDays(2) ==> Answers -2
native minusDays(_days)

Answers a copy of this date with the specified number of days subtracted.

This instance is immutable and unaffected by this method call.

Parameter must be an integer value.

This operation has no side effect (a new date is returned).

new Date(day = 1, month = 1, year = 2009).minusDays(1)
==> Answers 31/12/2008, a day back
new Date(day = 1, month = 1, year = 2009).minusDays(-1)
==> Answers 2/1/2009, a day forward
native minusMonths(_months)

Answers a copy of this date with the specified number of months subtracted.

Parameter must be an integer value.

This operation has no side effect (a new date is returned).

new Date(day = 1, month = 1, year = 2009).minusMonths(1)
==> Answers 1/12/2008, a month back
new Date(day = 1, month = 1, year = 2009).minusMonths(-1)
==> Answers 1/2/2009, a month forward
native minusYears(_years)

Answers a copy of this date with the specified number of years subtracted.

Parameter must be an integer value.

This operation has no side effect (a new date is returned).

new Date(day = 1, month = 1, year = 2009).minusYears(1)
==> Answers 1/1/2008, a year back
new Date(day = 1, month = 1, year = 2009).minusYears(-1)
==> Answers 1/1/2010, a year forward
native <(_aDate)

Documentation not found

native >(_aDate)

Documentation not found

<=(_aDate)

Documentation not found

>=(_aDate)

Documentation not found

between(_startDate, _endDate)

Answers whether self is between two dates (both inclusive comparison)

new Date(day = 2, month = 4, year = 2018).between(new Date(day = 1, month = 4, year = 2018), new Date(day = 2, month = 4, year = 2018))
==> Answers true
override native shortDescription()

Documentation not found

isWorkDay()

Answer whether the day is a work day (between monday and friday)

new Date(day = 13, month = 7, year = 2020).isWorkDay()
==> Answers true
isWeekendDay()

Answer whether the day is a weekend day (saturday or sunday)

new Date(day = 13, month = 7, year = 2020).isWorkDay()
==> Answers true

Singleton io

Represents an Input/Output event handler.

since 1.9.2

Estado
Atributo WollokDoc
const property eventHandlers

// TODO: merge handlers

const property timeHandlers

Documentation not found

property eventQueue

Documentation not found

property currentTime

Documentation not found

property exceptionHandler

Documentation not found

property domainExceptionHandler

Documentation not found

Comportamiento
Método WollokDoc
queueEvent(event)

Documentation not found

eventHandlersFor(event)

Returns a list of callbacks for the given event.

If the given event is not in the eventHandlers, it is added.

addEventHandler(event, callback)

Adds given callback to the given event.

removeEventHandler(event)

Removes given event from the eventHandlers.

timeHandlers(name)

Returns a list of callbacks for the given time event.

If the given time event is not in the timeHandlers, it is added.

containsTimeEvent(name)

Returns if given time event it's in the timeHandlers.

addTimeHandler(name, callback)

Adds given callback to the given time event.

removeTimeHandler(name)

Removes given event from the eventHandlers.

clear()

Removes all events from handlers.

flushEvents(time)

Runs all events in the eventQueue that are in the eventHandlers and

all time events in the timeHandlers for the given time.

runHandler(callback)

Runs the given callback.



lib.wlk

Singleton console

Console is a global wollok object that implements a character-based console device

called "standard input/output" stream

Método WollokDoc
native println(obj)

Prints a String with end-of-line character

native readLine()

Reads a line from input stream

native readInt()

Reads an int character from input stream

native newline()

Returns the system's representation of a new line:

- \n in Unix systems

- \r\n in Windows systems

Class OtherValueExpectedException

Exception to handle other values expected in assert.throwsException... methods

Método WollokDoc

Class AssertionException

Exception to handle difference between current and expected values

in assert.throwsException... methods

Estado
Atributo WollokDoc
const property expected

Documentation not found

const property actual

Documentation not found

Comportamiento
Método WollokDoc

Singleton assert

Assert object simplifies testing conditions

Método WollokDoc
that(value)

Tests whether value is true. Otherwise throws an exception.

assert.that(7.even())   ==> throws an exception "Value was not true"
assert.that(8.even())   ==> ok, nothing happens
notThat(value)

Tests whether value is false. Otherwise throws an exception.

see assert#that(value)

equals(expected, actual)

Tests whether two values are equal, based on wollok ==, != methods

assert.equals(10, 100.div(10)) ==> ok, nothing happens
assert.equals(10.0, 100.div(10)) ==> ok, nothing happens
assert.equals(10.01, 100.div(10)) ==> throws an exception
notEquals(expected, actual)

Tests whether two values are equal, based on wollok ==, != methods

const value = 5
assert.notEquals(10, value  3) ==> ok, nothing happens
assert.notEquals(10, value)     ==> throws an exception
doesNotThrowException(block)

Tests that a block does not throw any kind of exception. Block expects no parameters.

throwsException(block)

Tests whether a block throws an exception. Otherwise an exception is thrown.

assert.throwsException({ 7 / 0 })
==> Division by zero error, it is expected, ok
assert.throwsException({ "hola".length() })
==> throws an exception "Block should have failed"
throwsExceptionLike(exceptionExpected, block)

Tests whether a block throws an exception and this is the same expected.

Otherwise an exception is thrown.

assert.throwsExceptionLike(new BusinessException(message = "hola"),
{ => throw new BusinessException(message = "hola") }
=> Works! Exception class and message both match.
assert.throwsExceptionLike(new BusinessException(message = "chau"),
{ => throw new BusinessException(message = "hola") }
=> Doesn't work. Exception class matches but messages are different.
assert.throwsExceptionLike(new OtherException(message = "hola"),
{ => throw new BusinessException(message = "hola") }
=> Doesn't work. Messages matches but they are instances of different exceptions.
throwsExceptionWithMessage(errorMessage, block)

Tests whether a block throws an exception and it has the error message as is expected.

Otherwise an exception is thrown.

assert.throwsExceptionWithMessage("hola",{ => throw new BusinessException(message = "hola") }
=> Works! Both have the same message.
assert.throwsExceptionWithMessage("hola",{ => throw new OtherException(message = "hola") }
=> Works! Both have the same message.
assert.throwsExceptionWithMessage("chau",{ => throw new BusinessException(message = "hola") }
=> Doesn't work. Both are instances of BusinessException but their messages differ.
throwsExceptionWithType(exceptionExpected, block)

Tests whether a block throws an exception and this is the same exception class expected.

Otherwise an exception is thrown.

assert.throwsExceptionWithType(new BusinessException(message = "hola"),{ => throw new BusinessException(message = "hola") }
=> Works! Both exceptions are instances of the same class.
assert.throwsExceptionWithType(new BusinessException(message = "chau"),{ => throw new BusinessException(message = "hola") }
=> Works again! Both exceptions are instances of the same class.
assert.throwsExceptionWithType(new OtherException(message = "hola"),{ => throw new BusinessException(message = "hola") }
=> Doesn't work. Exception classes differ although they contain the same message.
throwsExceptionByComparing(block, comparison)

Tests whether a block throws an exception and compare this exception with other block

called comparison. Otherwise an exception is thrown. The block comparison

receives a value (an exception thrown) that is compared in a boolean expression

returning the result.

assert.throwsExceptionByComparing({ => throw new BusinessException(message = "hola"), { ex => "hola" == ex.message()}}
=> Works!.
assert.throwsExceptionByComparing({ => throw new BusinessException(message = "hola"), { ex => new BusinessException(message = "lele").className() == ex.className()} }
=> Works again!
assert.throwsExceptionByComparing({ => throw new BusinessException(message = "hola"), { ex => "chau!" == ex.message()} }
=> Doesn't work. The block evaluation resolves to a false value.
fail(message)

Throws an exception with a custom message.

Useful when you reach code that should not be reached.

override equals(value)

This method avoids confusion with equals definition in Object

Class StringPrinter

Documentation not found

Estado
Atributo WollokDoc
buffer

Documentation not found

Comportamiento
Método WollokDoc
println(obj)

Documentation not found

getBuffer()

Documentation not found



game.wlk

Singleton game

Documentation not found

Estado
Atributo WollokDoc
const visuals

Documentation not found

property running

Documentation not found

Comportamiento
Método WollokDoc
override initialize()

Documentation not found

native addVisual(positionable)

Adds an object to the board for drawing it.

Object should understand a position property

(implemented by a reference or getter method).

game.addVisual(pepita) ==> pepita should have a position property
addVisualCharacter(visual)

Adds an object to the board for drawing it. It can be moved with arrow keys.

That object should understand a position property

(implemented by a reference or getter method).

game.addVisualCharacter(pepita) ==> pepita should have a position property
native removeVisual(visual)

Removes an object from the board for stop drawing it.

game.removeVisual(pepita)
native hasVisual(visual)

Verifies if an object is currently in the board.

game.hasVisual(pepita)
native allVisuals()

Returns all visual objects added to the board.

game.allVisuals()
whenKeyPressedDo(event, action)

Adds a block that will be executed each time a specific key is pressed

see keyboard.onPressDo()

whenCollideDo(visual, action)

Adds a block that will be executed while the given object collides with other.

Two objects collide when are in the same position.

The block should expect the other object as parameter.

game.whenCollideDo(pepita, { comida => pepita.comer(comida) })
onCollideDo(visual, action)

Adds a block that will be executed exactly when the given object collides with other.

Two objects collide when are in the same position.

The block should expect the other object as parameter.

game.onCollideDo(pepita, { comida => pepita.comer(comida) })
onTick(milliseconds, name, action)

Adds a block with a specific name that will be executed every n milliseconds.

Block expects no argument.

Be careful not to set it too often :)

game.onTick(5000, "pepitaMoving", { => pepita.position().x(0.randomUpTo(4)) })
schedule(milliseconds, action)

Adds a block that will be executed in n milliseconds.

Block expects no argument.

game.schedule(5000, { => pepita.position().x(0.randomUpTo(4)) })
removeTickEvent(event)

Remove a tick event created with onTick message

game.removeTickEvent("pepitaMoving")
onSameCell(position1, position2)

Verifies if two positions are on the same cell of the board

game.onSameCell(game.at(2,3), game.at(2.4,3.2)) should return True
game.onSameCell(game.at(2,3), game.at(2.6,3.8)) should return False
native getObjectsIn(position)

Returns all objects in given position.

game.getObjectsIn(game.origin())
native say(visual, message)

Draws a dialog balloon with given message in given visual object position.

game.say(pepita, "hola!")
clear()

Removes all visual objects in game and configurations (colliders, keys, etc).

native colliders(visual)

Returns all objects that are in same position of given object.

currentTime()

Returns the current Tick.

flushEvents(time)

Runs all time event for the given time.

uniqueCollider(visual)

Returns the unique object that is in same position of given object.

stop()

Stops render the board and finish the game.

start()

Starts render the board in a new windows.

at(x, y)

Returns a position for given coordinates.

origin()

Returns the position (0,0).

center()

Returns the center board position (rounded down).

native title(title)

Sets game title.

native title()

Returns game title.

native width(width)

Sets board width (in cells).

native width()

Returns board width (in cells).

native height(height)

Sets board height (in cells).

native height()

Returns board height (in cells).

native ground(image)

Sets cells background image.

cellSize(size)

Sets cells size.

native doCellSize(size)

private

native boardGround(image)

Sets full background image.

native hideAttributes(visual)

Attributes will not show when user mouse over a visual component.

Default behavior is to show them.

native showAttributes(visual)

Attributes will appear again when user mouse over a visual component.

Default behavior is to show them, so this is not necessary.

native errorReporter(visual)

Allows to configure a visual component as "error reporter".

Then every error in game board will be reported by this visual component,

in a balloon message form.

sound(audioFile)

Returns a sound object. Audio file must be a .mp3, .ogg or .wav file.

tick(interval, action, execInmediately)

Returns a tick object to be used for an action execution over interval time.

The interval is in milliseconds and action is a block without params.

Class AbstractPosition

Documentation not found

Método WollokDoc
abstract x()

Documentation not found

abstract y()

Documentation not found

abstract createPosition(x, y)

Documentation not found

right(n)

Returns a new Position n steps right from this one.

left(n)

Returns a new Position n steps left from this one.

up(n)

Returns a new Position n steps up from this one.

down(n)

Returns a new Position, n steps down from this one.

say(element, message)

Draw a dialog balloon with given message in given visual object position.

allElements()

//TODO: Implement native

clone()

//TODO: Implement native

distance(position)

Returns the distance between given position and self.

clear()

Removes all objects in self from the board for stop drawing it.

override ==(other)

Two positions are equals if they have same coordinates.

override toString()

String representation of a position

round()

Returns a new position with its coordinates rounded

Class Position

Represents a position in a two-dimensional gameboard.

It is an immutable object since Wollok 1.8.0

Estado
Atributo WollokDoc
const x

Documentation not found

const y

Documentation not found

Comportamiento
Método WollokDoc
override x()

Documentation not found

override y()

Documentation not found

override createPosition(_x, _y)

Documentation not found

Class MutablePosition

Documentation not found

Estado
Atributo WollokDoc
x

Documentation not found

y

Documentation not found

Comportamiento
Método WollokDoc
override x()

Documentation not found

override y()

Documentation not found

override createPosition(_x, _y)

Documentation not found

goRight(n)

Documentation not found

goLeft(n)

Documentation not found

goUp(n)

Documentation not found

goDown(n)

Documentation not found

Singleton keyboard

Keyboard object handles all keys movements. There is a method for each key.

keyboard.i().onPressDo { game.say(pepita, "hola!") }
=> when user hits "i" key, pepita will say "hola!"
keyboard.any().onPressDo { game.say(pepita, "you pressed a key!") }
=> any key pressed will activate its closure
Método WollokDoc
any()

Documentation not found

num(n)

Documentation not found

letter(l)

Documentation not found

arrow(a)

Documentation not found

num0()

Documentation not found

num1()

Documentation not found

num2()

Documentation not found

num3()

Documentation not found

num4()

Documentation not found

num5()

Documentation not found

num6()

Documentation not found

num7()

Documentation not found

num8()

Documentation not found

num9()

Documentation not found

a()

Documentation not found

b()

Documentation not found

c()

Documentation not found

d()

Documentation not found

e()

Documentation not found

f()

Documentation not found

g()

Documentation not found

h()

Documentation not found

i()

Documentation not found

j()

Documentation not found

k()

Documentation not found

l()

Documentation not found

m()

Documentation not found

n()

Documentation not found

o()

Documentation not found

p()

Documentation not found

q()

Documentation not found

r()

Documentation not found

s()

Documentation not found

t()

Documentation not found

u()

Documentation not found

v()

Documentation not found

w()

Documentation not found

x()

Documentation not found

y()

Documentation not found

z()

Documentation not found

alt()

Documentation not found

backspace()

Documentation not found

control()

Documentation not found

del()

Documentation not found

center()

Documentation not found

down()

Documentation not found

left()

Documentation not found

right()

Documentation not found

up()

Documentation not found

enter()

Documentation not found

minusKey()

Documentation not found

plusKey()

Documentation not found

shift()

Documentation not found

slash()

Documentation not found

space()

Documentation not found

Class Key

Documentation not found

Estado
Atributo WollokDoc
const property keyCodes

Documentation not found

Comportamiento
Método WollokDoc
onPressDo(action)

Adds a block that will be executed always self is pressed.

keyboard.i().onPressDo { game.say(pepita, "hola!") }
=> when user hits "i" key, pepita will say "hola!"

Class Sound

Wollok Game Sound object

Estado
Atributo WollokDoc
const property file

Documentation not found

Comportamiento
Método WollokDoc
override initialize()

Documentation not found

native play()

Plays the file's sound.

A sound can only be played once.

native played()

Answers whether the sound has been played or not.

native stop()

Stops playing the sound and disposes resources.

native pause()

Pauses the sound.

Throws error if the sound is already paused or if the sound hasn't been played yet.

native resume()

Resumes playing the sound.

Throws error if the sound is not paused.

native paused()

Answers whether the sound is paused or not.

native volume(newVolume)

Changes absolute volume, values must be between 0 and 1.

mySound.volume(0)  => The sound is now muted.
mySound.volume(0.5)  => New volume is half of the original sound's volume
mySound.volume(mySound.volume()0.5) => New volume is half of the current volume
native volume()

Answers the volume of the sound.

native shouldLoop(looping)

Sets whether the sound should loop or not.

native shouldLoop()

Answers whether the sound is set to loop or not.

Class Tick

Documentation not found

Estado
Atributo WollokDoc
interval

Milliseconds to wait between each action

const name

The ID associated to the tick event to be created

const action

Block to execute after each interval time lapse

const inmediate

Indicates whether the action will be executed as soon

as the loop starts, or it will wait to the first time interval.

Comportamiento
Método WollokDoc
start()

Starts looping the action passed in to the tick

object when it was instantiated.

stop()

Stops looping the tick.

reset()

Stops and starts looping the tick.

interval(milliseconds)

Updates the tick's loop interval.

isRunning()

Indicates whether the tick is currently looped or not.



mirror.wlk

Class InstanceVariableMirror

Documentation not found

Estado
Atributo WollokDoc
const target

Documentation not found

const property name

Documentation not found

Comportamiento
Método WollokDoc
value()

Documentation not found

valueToString()

Documentation not found

override toString()

Documentation not found

Class ObjectMirror

Represents an object capable of give information of another object.

It offers a reflection mechanism that is completely decoupled

from the object whose structure is being introspected.

Estado
Atributo WollokDoc
const property target

Documentation not found

Comportamiento
Método WollokDoc
native resolve(attributeName)

Accesses a variable by name, in a reflexive way.

native instanceVariableFor(name)

Retrieves a specific variable for target object. Expects a name

native instanceVariables()

Answers a list of instance variables for target object



vm.wlk

Singleton runtime

Object for Wollok implementation for runtime decisions

Método WollokDoc
native isInteractive()

true if running REPL, false otherwise