Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of OO languages where object immutability can be compiler enforced

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.

like image 856
Simeon Avatar asked Jan 19 '11 15:01

Simeon


People also ask

How do you enforce immutability?

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.

What is an example of immutability?

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.

What is an immutable language?

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.


2 Answers

Functional programming languages like OCAML, Haskell, and Erlang.

like image 111
Apalala Avatar answered Nov 09 '22 18:11

Apalala


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"
like image 34
pblasucci Avatar answered Nov 09 '22 18:11

pblasucci