Which programming languages other than C++ support the concept of a constant class method? That is, what languages allow t开发者_开发技巧he programmer to constrain a method in such a way that it is guaranteed not to change the state of an object to which the method is applied?
Please provide examples or references in your answer.
Haskell, since it's purely functional.
Actually, every value/method is constant in Haskell even though mutable state/IO can be modelled through a mathematical construct called monad.
All purely functional languages are all const
by default because purely functional languages have no state to be changed.
I believe that Fortran (95 or greater I think) has what you are looking for. Coincidentally enough called "pure subroutines".
http://www.soks.org/view/Fortran95ForFortran77Programmers#pure_routines
http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/index.jsp?topic=/com.ibm.xlf91a.doc/xlflr/pure.htm
ConstJava and Javari are two variations of Java that support the concept of a constant method. ConstJava has been obsoleted by Javari, though.
Since you tagged this as C++, I think you mean const
method like this:
class A {
int e;
public:
int doSomething() const {
// ++ e; // Compiler error, change data-member in read-only structure
return e+1; // OK.
}
};
(Although C++'s const is not a true-const because of the mutable
members.)
Then I'm only aware of C++, D2, and all those functional languages supporting this.
- C# doesn't support
const
methods but you can make all membersreadonly
. You can also make areadonly
wrapper class/subclass. Java doesn't have the const keyword, but like C# you can make all membersfinal
. - All functional languages use const correct methods by default because the functions are pure, but whether they support Object-oriented programming is another question.
According to this Wikipedia entry, this feature is not available in many other object-oriented languages such as Java and C# or in Microsoft's C++/CLI.
Purely functional languages like Haskell, Curry, http://en.wikipedia.org/wiki/Ωmega_interpreter">Ωmega do support *mandate* this feature.
Perhaps you could write a custom attribute in .Net. The objects you pass in though, may all have to inherit from the same class i.e. EntityBase so you can manually ensure the state is the same.
精彩评论