Difference between "=" and ":=" on assignment

Monkey Forums/Monkey Beginners/Difference between "=" and ":=" on assignment

consty(Posted 2014) [#1]
Hi everyone, I notice that sometimes you can initialize a variable with the "=" character and others with ":=".

Strict
Function Main:Int()
	Local a:String = "OK1"
	Local b := "OK2"
	Return 0
End


I remember when studying Pascal, that ":=" character has very special meaning, however I don't know in monkey exactly what it is apart from typing convenience.

What does the syntax suggests?


ImmutableOctet(SKNG)(Posted 2014) [#2]
In Monkey, ":=" 'automates' type-declaration. Basically the type of whatever you set it to will be used. This is useful for local variables, and constant variables which are meant to be aliases for other constants. This can be done with objects/classes as well. It's useful in most situations, but overusing it can be terribly messy. It's "best" to use it for small local variables where the attempt is to make the type seem agnostic or unimportant. For example with a 'Stream' called 'S', you could do: "Local B:= S.ReadByte()" so then if there ever is such a type as "Byte" in Monkey, you won't ever have an issue. This is also good for caching data without caring about the type (Array and list lengths for example). It's also very useful for generic/template classes. To put it simply, this is just the lazy man's tool. C++ has the auto keyword now (As of C++11), which does the same sort of thing.


Pharmhaus(Posted 2014) [#3]
The := allows you to automatically detect the variable type.
If you are using Strict mode you need to always define the variable type otherwise.
This is valid:
Local b:= New StringList

And will automatically detect that 'b' needs to be a StringList
but this is not:
Local b = New StringList

Because it doesn't know what 'b' is meant to be.
In order to get it working you need to tell what 'b' is meant to be. (StringList)
Local b:StringList = New StringList

The := is very handy for all the generics because they are usually very long and hard to type over and over again, so it saves you mostly time.
In some circumstances it is also very useful to not define the type of the variable because this leaves sometimes more room for changes.


consty(Posted 2014) [#4]
I see now, it's good to have this as an extra option.