What is the difference between an array and a literal array in Smalltalk?

In addition to size.

For instance:

|arr|. arr := Array new: 10 

and

 #(element1,element2, ...) 
+5
source share
2 answers

In both forms, the created object will have the same type and the same elements. The main difference is that when using Array with: you get a new instance every time the code is executed, and with #( ) you get an instance created when the method was accepted / compiled, so every time the code is executed by the instance from the array same.

Consider the following code:

 doSomething array := #(6 7 8). Transcript show: array. array at: 1 put: 3. 

the first time you do doSomething, everything will be fine. The second time you get 3, 7, 8 printed, because the array is the same that was changed the previous time the method was called.

So, you should be careful when using literals and basically leave them for cases where they will not be mutated.

+5
source

Consider this method in an example class with an instance variable threshold:

 Example >> #threshold ^threshold Example >> #threshold: anInteger threshold := anInteger Example >> #initialize threshold := 0 Example class >> #new ^super new initialize Example >> testArraySum | a | a := #(4 8 10). a sum > threshold ifTrue: [ a at: 1 put: a first - 2 ]. ^a sum 

Now, if you are reading testArraySum code, if the threshold does not change, it should always repeat the same thing, right? Try that you start setting a fixed value of a, and then subtract (or not, depending on the threshold, but we said that it is fixed) a fixed amount, so it should be ... 20.

Ok if you rate

 Example new testArraySum 

several times, you get 20,18, 16 ... because array # (4 8 10) is changing. On the other hand,

 Example >> testConstantArraySum | a | a := Array new: 3. a at: 1 put: 4; at: 2 put: 8; at: 3 put: 10. a sum > threshold ifTrue: [ a at: 1 put: a first - 2 ]. ^a sum 

really constant.

+3
source

Source: https://habr.com/ru/post/1264078/


All Articles