4.5. Methods With Syntax Support¶
Vala recognizes some methods with certain names and signatures and provides syntax support for them. For example, if a type has a contains() method objects of this type can be used with the in
operator. The following table lists these special methods. T and Tn are only type placeholders in this table and meant to be replaced with real types.
Indexers |
|
---|---|
|
Index access: |
|
Index assignment: |
Indexers with multiple indices |
|
---|---|
|
Index access:
|
|
Index assignment: |
Indexers |
|
---|---|
|
Index access: |
|
Index assignment: |
Others |
|
---|---|
|
Slicing: |
|
|
|
Support within string templates:
|
|
Iterable via |
|
Iterable via |
The Iterator type can have any name and must implement one of these two protocols:
|
Standard iterator protocol iterating
until .next() returns |
|
Alternative iterator protocol: If
the iterator object has a
.next_value() function that returns a
nullable type then we iterate by calling
this function until it returns |
This example implements some of these methods:
public class EvenNumbers {
public int get(int index) {
return index * 2;
}
public bool contains(int i) {
return i % 2 == 0;
}
public string to_string() {
return "[This object enumerates even numbers]";
}
public Iterator iterator() {
return new Iterator(this);
}
public class Iterator {
private int index;
private EvenNumbers even;
public Iterator(EvenNumbers even) {
this.even = even;
}
public bool next() {
return true;
}
public int get() {
this.index++;
return this.even[this.index - 1];
}
}
}
void main() {
var even = new EvenNumbers();
stdout.printf("%d\n", even[5]); // get()
if (4 in even) { // contains()
stdout.printf(@"$even\n"); // to_string()
}
foreach (int i in even) { // iterator()
stdout.printf("%d\n", i);
if (i == 20) break;
}
}