This language bar is your friend. Select your favorite languages!

Idiom #90 Read-only outside

Expose a read-only integer x to the outside world while being writable inside a structure or a class Foo.

struct Foo {
    x: usize
}

impl Foo {
    pub fn new(x: usize) -> Self {
        Foo { x }
    }

    pub fn x<'a>(&'a self) -> &'a usize {
        &self.x
    }

    pub fn bar(&mut self) {
        self.x += 1;
    }
}
package Foos is
      
   type Foo is private;
      
   function X (Self : Foo) return Integer;
      
private
   type Foo is
      record
         X : Integer;
      end record;
      
end Foos;
   
package body Foos is
      
   function X (Self : Foo) return Integer is (Self.X);
      
end Foos;
struct Foo
{
    private int _x;
    int x() {return _x;}
}
type Foo struct {
	x int
}

func (f *Foo) X() int {
	return f.x
}
module Foo (Foo, getX) where

import Data.IORef

data Foo = Foo { xRef :: IORef Integer }

getX = readIORef . xRef
const Foo = function Counter () {
  let n = 0
  Object.defineProperty (this, 'value', {get: () => n++})
}
{
  const counter = new Foo ()
  counter.value // 0
  counter.value // 1
}
class Foo {
	private $x;
	
	public function getX() {
		return $this->x;
	}
}
class Foo {
	private $x;
	
	public function getX() : int {
		return $this->x;
	}
}
type Foo = class
  private fx: integer;
  public property x: integer read fx;
end;
class Foo(object):
    def __init__(self):
        self._x = 0

    @property
    def x(self):
        """
        Doc for x
        """
        return self._x
class Foo

  def initialize
    @x = rand(10)
  end

  def x
    @x
  end

end


Do you know the best way to do this in your language ?
New implementation...

Idiom created by

bbtemp