View · Search · Index
No registered users in community xowiki
in last 10 minutes

Re: [Xotcl] constant/immutable property

From: Gustaf Neumann <neumann_at_wu-wien.ac.at>
Date: Wed, 30 Nov 2011 00:02:05 +0100

On 29.11.11 18:39, Victor Mayevski wrote:
> Hello Gustaf,
>
> What would be a good way to define a constant/immutable
> property/variable in Next?

Dear Victor,

Below is a short study to set all current instance variables
of an object immutable based on variable traces. To
implement the immutable functionality on the property level
is more involved, since one has to handle
default/non-default cases, and one has to register the
traces at the right time for every object creation.

Maybe this simple study helps already

-gustaf neumann

==============================================================
package req nx
package req nx::test
package req nx::trait

::nx::Class create C {
   :require trait nx::traits::callback

   #
   # Method called via trace to reject write operations
   #
   :public method reject {name sub op} {
     error "$op operation on variable $name of object [self] is not allowed"
   }

   #
   # Method to make all currently defined variables of an object
   # immutable
   #
   :public method immutable {} {
     foreach v [:info vars] {
       ::trace add variable :$v write [:callback reject]
     }
   }
   :create c1 {
     set :x 1
     set :y 2
   }
}

c1 immutable
? {c1 eval {set :x}} 1
? {c1 eval {set :y}} 2
? {c1 eval {set :x 1}} {can't set ":x": write operation on variable :x of object ::c1 is not allowed}
? {c1 eval {set :z 3}} 3