[Xotcl] constant/immutable property

Gustaf Neumann neumann at wu-wien.ac.at
Wed Nov 30 00:02:05 CET 2011


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



More information about the Xotcl mailing list