i have a class at smalltalk in pharo.
i create an instance in global dictionary which is smalltak,
Smalltalk at:#asd put: myobject new.
then i write this code to workspace, mistakely.
Smalltalk at:asd put: myobject new.
and this gives to me error, continuously,
when a press a key from keyboard, i get error my object does not understand, is this byteArray, like that.
how can i solve this issue?
or how can i reset global dictionary?
Ok, this is a fun question.
First of all I suggest you not to do things like that, because globals are usually used for storing classes in them.
Now the cause of the problem is that you don't have to declare vars in workspace, it will create a new war for every name you use. By default new var is nil, so what you've done was putting a nil key in the dictionary
To remove it execute this thing:
Smalltalk globals removeKey: nil ifAbsent: [ ]
Now, if you want to have a unique instance of you class, I'd suggest you using a singleton pattern. This implies defining class instance variable (e.g. default) and a class method:
default
^ default ifNil: [default := self new ].
This will create new instance first time you run it, and then keep it and return it whenever you want it later.
Related
I try to implement a specific Dictionary class in Smalltalk which needs to override the #at:put: method in Pharo and Squeak. But when I create a class having #at:put: as an instance method and I send that methode, I get the error:
Error: Instances of '#SortedDictionary' class are not indexable
The class definition is as follows:
Dictionary subclass: #SortedDictionary
instanceVariableNames: 'index'
classVariableNames: ''
category: 'MyApplication'
An instance is created by overriding new:
!SortedDictionary class methodsFor: 'creation' stamp: 'nanitous 9/28/2015 19:17'!
new
super new.
^self initialize! !
An instance is initialized with:
initialize
index := Heap new.
^self
And the instance method is defined as:
at: anIndex put: aValue
index add: anIndex.
^self at: anIndex put: aValue! !
And I test with the script in a workspace:
| d |
d := SortedDictionary new.
d at: 1 put: 3.
I tried to make a class not derived from #Dictionary but from #Object and used an instance variable dict containing an instance of #Dictionary, but with the same result.
Why can't I override #at:put: and and how can I override this method?
EDIT
Thanks to #lurker and #aka.nice I should have done the following:
!SortedDictionary class methodsFor: 'creation' stamp: 'nanitous 9/28/2015 19:17'!
new
^super new initialize! !
Doing this wrong was outright silly! In the original and wrong code I was trying to index a nil object.
And:
!SortedDictionary instance methodsFor: 'accessing' stamp: 'nanitous 9/28/2015 19:17'!
at: anIndex put: aValue
index add: anIndex.
^super at: anIndex put: aValue! !
Well, I never came to solve this one before solving the #new issue.
Thanks again to everyone taking the trouble to help out here!
Generally, an instance of collection (more precisely a subclass of Collection) is created with #new:, not #new.
The parameter passed to new: is a size, either the size for a fixed size collection (like Array new: 3), or some pre-allocated size for variable size collection (like OrderedCollection, Set, Dictionary, ...).
From the stamp, I guess you are on a Squeak or Pharo flavour, so I will continue explanation with these dialects, it may slightly vary for other flavours.
In Squeak/Pharo, see the definition of HashedCollection class>>new:
new: nElements
"Create a Set large enough to hold nElements without growing"
^ self basicNew initialize: (self sizeFor: nElements)
It sends initialize: not initialize.
So the first thing you have to do is to define initialize: at instance side of your class, and the second thing is to remove definition of new/new: overriding these is rarely ever needed in Squeak/Pharo.
Currently you have a problem in your #new definition, when you tell self initialize what is self exactly? it is the class SortedDictionary, so you initialize the class, not the instance! And you answer the class, not the newly created instance, so you later send at:put: to the class...
It should have been something like newInstance := super new. ^newInstance initialize.
Last, your at:put: definition will loop forever, it should invoke super at: ... put: ...
A couple of nits to pick.
When you write Smalltalk code as text, such as we're doing here,
you can use the format
{classname|blank} {class|blank} >> methodHead
where the first field names the class, the second field tells whether it is class side or instance side, and the '>>' indicates start of source code.
If you don't name the class, we assume the same class as the last one named.
If you don't say it is class side, we assume it is instance side.
So your methods would be written as
SortedDictionary class>>new
^super new
initialize
>>initialize
index := Heap new
>>at: anIndex put: aValue
index add: anIndex.
^super at: anIndex put: aValue
Second, since you're defining a subclass, you only need to define
your own #new (and/or #new:) method if you must override the one that is otherwise inherited from the superclasses. (But you knew that).
Third, whenever you write an #initialize method, you want to get in the habit of writing 'super initialize.' as the first line thereof.
And once you get into said habit, you'll want to get out of the habit of writing your #new methods starting with '^super new initialize', and get into the habit of starting them with 'self basicNew initialize' instead.
I know, everyone learns to do it that other way. (Sigh.)
But that is soooooo wrong.
Extra points if you can figure out why this is so. ;-)
I know that for an instance variable all I have to do is put it inside the initialise method in the instance side and assign it a default value. But how I do this for class variable ? I tried to create an initialise method at class side but it did not give my variable a default value so I had to do this in one of my methods
pythonString ifNil:[pythonString := '']
But I don't like this approach.
I also found this for squeak , http://forum.world.st/Howto-initialize-class-variables-td1667813.html again I don't like this approach either. Is there a proper way of doing this. In Python it was fairly simple case of assignment why is it so cryptic for Pharo ?
First of all I hope that you are talking about instance variable of a class object (not a thing that you define on instance side as "class variable").
initialize is working, but it's being run upon instance creation. And instance (a class object) exists already when you define initialize method.
So when you define your class for the first time, you should run it by yourself e.g. YourClass initialize, bun later each time you load your class into system it should be initialised.
How can we initialize a class variable in Visualworks Smalltalk and destroy it after its use?
I want to know about ClassVariables. NOT ClassInstanceVariables.
I am implementing Singleton pattern and here is my code
MyClass class>> aClasMethod
aClassVariable isNil ifTrue:[
aClassVariable := 'I am a variable'.
]
^aClassVariable.
Once the variable is created, I am not able to destroy it.
i.e Next time I run my code, I see that the class variable is retaining its previous value.
How can I avoid this?
I tried this:
MyClass allInstances do: [:inst |
inst become: nil
].
But of no use.
The best way is simply to add a class method to set the class variable to nil and then call it whenever it's an appropriate time to clear it. I do this all the time with the Singleton pattern.
i think we usually use singleton pattern so that we only have one object. I don't know why do you want to store a string value in the class variable. Try to store a object so you will have only one copy of that specific object and store values in the instance variables. so that specific object has only some specific values. Then in future if u need to update the values stored in instance variable then make one more method updateValues and do everything in that.
I'm a bit of a novice when it comes to Squeak Smalltalk, so I'll probably done something wrong or made an erroneous assumption about how Squeak should work. Still, I'd like to know where I went wrong...
I tried to make class Blower derived from Array. Blower is basically an Array, but with an additional instance variable called index and some methods. I thought the initialize method would be automatically run when I created a new object, and that it would initialize both the array and the index variable, but this doesn't seem to happen. If I run initialize "manually" later though, it works as expected.
Array variableSubclass: #Blower
instanceVariableNames: 'index'
(...)
Blower >> initialize
super initialize.
1 to: self size do: [ :ix | self at: ix put: ix ].
self shuffle.
index := 1.
If I do the following in a workspace:
blower := Blower new: 10.
blower inspect.
Inspect-window shows (Not what I expected):
\#( nil nil nil nil nil nil nil nil nil nil )
index: nil
If I run initialize manually, Inspect-window is correct:
blower initialize.
\#( 6 4 1 10 2 8 3 ... )
index: nil
So why doesn't initialize run when I create the Blower and set it up correctly?
Is there anyway to automate this so it happens on creation? Ie. getting initialize to work?
Look at the method ArrayedCollection class >> new. It overrides new to call new: with 0 as a parameter. This replaces the default implementation of new in Behavior which calls initialize. If you really want to do this, implement new and new: as class methods in your class. In each case, call super then call initialize.
new
^super new initialize
new: sizeRequested
^(super new: sizeRequested) initialize
Having said all that, it's a really bad idea to subclass from Array. Ask yourself "Is it reasonable for me to use a Blower any place I currently use an Array?". If not, it's not a good subclass. Any time you subclass from a collections class you're almost always doing it wrong. What you want is a class called Blower which is a subclass of Object and contains two instance variables - one for the array and one for the index. Your class will now initialize normally. For any operations you want to send to the array, write a method in the Blower to delegate it to the instance variable.
What David Buck said is correct, but there is a few more things to add, specific to Squeak:
Some collections invoke #initialize: instead of #initialize at instance creation (see for example HashedCollection)
Some other could send both #initialize then #initialize: (see SharedQueue)
But Array class>>new: has a specific implementation that completely bypasses initialize (for the sake of speed, it is known that there is nothing required for initializing an Array)
As David said, it is generally a bad idea to subclass Array, and looking at Squeak, there are too many counter-examples already.
I'm using Pharo 3.0
Is there a way to remove all objects from memory? I've tried closing and re-opening my image, but it appears that everything is still in memory.
For example, I had:
General Ledger --> Spending Manager and both setup as a singleton:
GeneralLedger>>new
instance isNil ifTrue: [instance := super new].
^ instance
SpendingManager>>new
instance isNil ifTrue: [instance := super new].
^ instance
and messed up somewhere along the way when instantiating Spending Manager - i.e., I returned the instance of General Ledger and not the instance of Spending Manager I guess?
Now when I load my image and try to do CTRL+P on:
spnder:=SpendingManager new. I get:
spnder:=SpendingManager new. a GeneralLedger
I've even removed the inheritance from SpendingManager so that it now inherits from Object, but this still happens.
How did you declare instance?
In such case it should be declared like this:
YourSUperClass classInstanceVariables: 'instance'.
Maybe you did it correctly, but it's unclear from your post (and the hierarchy between your two classes is unclear too).
Your main problem is the usage of super new.
When you create an instance of the subclass for the first time, it will send super new which will:
either return an already initialized instance of superclass
or register an instance of the subclass as the superclass singleton
You should use instance := self basicNew initialize instead.
Also you can write the whole thing
^instance ifNil: [instance := self basicNew initialize]
The other possibility is just to NOT redefine new in subclass, the new from superclass will just work.
And last thing, to remove the initialization, just inspect the class and modify the 'instance' class instance variable directly from the Editor (select this field, type nil and accept).