2

Is there any way to initialize a Sequential value not in one fellow swoop?

Like, can I declare it, then use a for loop to populate it, step by step?

As this could all happen inside a class body, the true immutability of the Sequential value could then kick in once the class instance construction phase has been completed.

Example:

Sequential<String> strSeq;

for (i in span(0,10)) {
    strSeq[i] = "hello";
}

This code doesn't work, as I get this error:

Error:(12, 9) ceylon: illegal receiving type for index expression: 'Sequential' is not a subtype of 'KeyedCorrespondenceMutator' or 'IndexedCorrespondenceMutator'

So what I can conclude is that sequences must be assigned in one statement, right?

4

3 回答 3

4

是的,一些语言保证取决于顺序对象的不变性,因此语言必须保证不变性——它不能只相信你在初始化完成后不会改变它:)

通常,您在这种情况下所做的是构建某种集合(例如ArrayListfrom ceylon.collection),根据需要对其进行变异,然后.sequence()在完成后获取它。

您的具体情况也可以写成顺序文字的理解:

String[] strSeq = [for (i in 0..10) "hello"];
于 2017-09-06T20:52:51.647 回答
3

用于创建序列文字的方括号不仅接受以逗号分隔的值列表,还接受用于理解:

String[] strSeq = [for (i in 0..10) "hello"];

你也可以同时做这两个,只要理解是最后的:

String[] strSeq = ["hello", "hello", for (i in 0..8) "hello"];

在这种特定情况下,您也可以这样做:

String[] strSeq = ["hello"].repeat(11);

您还可以通过嵌套获得一系列序列:

String[][] strSeqSeq = [for (i in 0..2) [for (j in 0..2) "hello"]];

你可以做笛卡尔积(注意这里嵌套的理解不在方括号中):

[Integer, Character][] pairs = [for (i in 0..2) for (j in "abc") [i, j]];

Foo[]是 的缩写Sequential<Foo>x..y翻译为span(x, y)

于 2017-09-06T20:51:41.350 回答
3

如果您预先知道要创建的序列的大小,那么一种非常有效的方法是使用Array

value array = Array.ofSize(11, "");
for (i in 0:11) {
    array[i] = "hello";
}
String[] strSeq = array.sequence();

另一方面,如果您知道预先的尺寸,那么,如 Lucas 所述,您需要使用以下任一:

  • 理解,或
  • 某种可增长的数组,例如ArrayList.
于 2017-09-06T22:05:28.910 回答