Can anyone give me a list of languages where class immutability can be compiler enforced and tested easily ?
I need to be able to do something like:
class immutable Person {
private String name = "Jhon"; // lets say the String is mutable
public Person(String name) {
this.name = name; // ok
}
public void setName(String newName) {
this.name = newName; // does not compile
}
public void getName() {
return this.name; //returns reference through which name can't be mutated
}
private void testImmutability() {
getName().setFirstChar('a'); // does not compile
}
}
EDIT:
For a little more clarification, see here.
On value types (which usually should be immutable from a design perspective), immutability can be enforced by applying the readonly modifier on the type. It will fail to compile if it contains any members that are not read-only.
String is an example of an immutable type. A String object always represents the same string. StringBuilder is an example of a mutable type. It has methods to delete parts of the string, insert or replace characters, etc.
Immutability is the idea that data or objects should not be modified after they are created. This concept has permeated throughout computing, and it is a core tenant of functional programming languages such as Haskell, Erlang, and Clojure.
Functional programming languages like OCAML, Haskell, and Erlang.
F# and Scala both have the ability to created compiler-enforced immutable types (i.e. classes).
The following shows the basics in F#...
// using records is the easiest approach (but there are others)
type Person = { Name:string; Age:int; }
let p = { Person.Name="Paul";Age=31; }
// the next line throws a compiler error
p.Name <- "Paulmichael"
Here's the equivalent Scala. Note that you can still make mutable objects by using var
instead of val
.
class Person(val name: String, val age: Int)
val p = new Person("Paul", 31)
// the next line throws a compiler error
p.name = "Paulmichael"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With