Getter and Setter Properties in Monkey
Submitted by Earok on Fri, 01/04/2013 - 12:36Monkey has a lot of curious functionality that I'm still discovering.
For instance, recently I discovered that you can do properties by treating Methods as Fields, and even have multiple setters to handle different types of value. For example, this Monkey code:
Function Main()
'Note that myClass is implicitly typed, similar to C# var keyword.
Local myClass:= New MyClass
myClass.MyString = "HELLO WORLD!"
Print myClass.MyString
myClass.MyString =["Ignore this", "Print this", "But ignore this too"]
Print myClass.MyString
End
Class MyClass
Public
'Getter, returns the value with numbers on the end
Method MyString:String()
Return _myString + " 12345"
End
'First Setter, converts the value to lower case
Method MyString:Void(value:String)
_myString = value.ToLower()
End
'Second Setter, grabs the second element from a string array
Method MyString:Void(value:String[])
_myString = value[1]
End
Private
'Private field
Field _myString:String
End
Will print:
hello world! 12345
Print this 12345