Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Creating one get/set method for a class

    Hi

    Was coding when I recalled this little hack which I would like to share with you.
    In other programming languages you can have get and set in the same method as shown below.

    Code:
    . mata mata clear
    . mata:
    :     class demo
    >     {
    >         private:
    >             real scalar value
    >         public:
    >             get_set_value()
    >     }
    :    
    :         function demo::get_set_value(|real scalar value)
    >         {
    >             if (value == .) return(this.value)
    >             else this.value = value
    >         }
    :    
    :     d = demo()
    :     // Set value
    :     d.get_set_value(4)
    :     // Get value
    :     d.get_set_value()
      4
    . end
    Kind regards

    nhb

  • #2
    Yes, that is essentially how many official Mata functions look like.

    I prefer to code
    Code:
    if (args() == 0) return(this.value)
    instead of
    Code:
    if (value == .) return(this.value)
    https://twitter.com/Kripfganz

    Comment


    • #3
      I agree with Sebastian, better use args(). Plus you can delete else, as this line will not be reached if the if condition is true.

      Comment


      • #4
        Dear both I too use args() from time to time.
        But that was not my point.
        I wanted to show a method definition that did update a class property when given an argument and otherwise returned property content.
        Kind regards

        nhb

        Comment

        Working...
        X