Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising Sequential values with for loop?

Tags:

ceylon

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?


1 Answers

Yes, several language guarantees hinge on the immutability of sequential objects, so that immutability must be guaranteed by the language – it can’t just trust you that you won’t mutate it after the initialization is done :)

Typically, what you do in this situation is construct some sort of collection (e. g. an ArrayList from ceylon.collection), mutate it however you want, and then take its .sequence() when you’re done.

Your specific case can also be written as a comprehension in a sequential literal:

String[] strSeq = [for (i in 0..10) "hello"];
like image 187
Lucas Werkmeister Avatar answered Jan 05 '26 05:01

Lucas Werkmeister



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!