List of OO languages ​​where object immutability can be enforced

Can someone give me a list of languages ​​where the immutability of a class can be forced and checked by the compiler?

I need 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:

See here for more explanation.

+6
language-agnostic immutability programming-languages language-design
source share
4 answers

Functional programming languages ​​such as OCAML, Haskell, and Erlang.

+5
source share

Joe-e

From language specification

3.4 Immutable Types

A type T is immutable if and only if it implements the token interface org.joe_e.Immutable according to the type overlay. The (empty) org.joe_e.Immutable for the implementation of Joe-E should be provided. the intuition behind an immutable object is that such an object cannot be changed (mutated) in any observable path, and objects after fields of an immutable object cannot be accessed either. The contents of the immutable fields of objects and any objects accessible from an immutable object should not change after the object is built. With the exception of library classes, to explicitly implement Immutable , an immutable class must satisfy additional linguistic restrictions, (x4.4), to verify this property. Library classes that cannot be automatically verified and considered immutable must be carefully checked manually for the possibility of modifying their contents. Note that immutability does not impose any restrictions on any local variables, an immutable class. He also says nothing about the variability of arguments passed to methods. This only applies to values ​​stored in objects and objects reachable from an immutable class of fields

He also introduces useful concepts about powerless and disinterested types.

+4
source share

F # and Scala both have the ability to create immutable types associated with the compiler (i.e. classes).

Below are 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 is the Scala equivalent. Note that you can still create mutable objects 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" 
+3
source share

The programming language D (version D2) has immutability. This one has OOP, but immutability is rather a concept from a functional pl. There it is called purity .

+3
source share

All Articles