Monkey Documentation

Keyword Property

Declares method as property.

Syntax

Method Identifier: ReturnType ( Parameters ) [ Property ] [ Abstract ] [ Final ]
Statements...
End [ Method ]

Description

The Property keyword declares that a method is acting as a class property. Properties are generally used to access a single (usually private) field in a controlled fashion.

Unlike a standard method, a property acts as a proxy for a field, and so can be written to (and read from) using the same syntax as for a field or variable. For example, reading a property:

result = myobject.MyProperty

Note that because it's acting like a field, no method-call brackets are required.

Writing to a property:

myobject.MyProperty = value

Properties are usually declared in pairs with the same name:

  • a 'read' version with no parameters which reads a specific field, and;
  • a 'write' version with a single parameter which writes to the same field.
(In the second example above, the value being assigned is the parameter defined in the 'write' property.)

Properties with multiple parameters cannot use this shortened syntax and must be called in the same way as a standard method.

See also

Method | Abstract | Final
Language reference (Methods)

Examples

' Runnable example...

Class BankAccount

    Private

        Field balance:Int

    Public

        Method Balance (dollars:IntProperty

            If dollars > 1000000
                Print "Sent for security check!"
            Else
                balance = dollars
            Endif

        End

        Method Balance:String () Property
            Return "$" + balance
        End

End

Function Main ()

    Local account:BankAccount = New BankAccount

    account.Balance = 50 ' 00000 ' Join to trigger security check!

    Print account.Balance

End