#2637 Fields and local fields by default is immutable

danykey Mon 11 Sep


Thanks for Fantom!

So, I am a bit confused because F not supports const(read-only) for local vars. If we talk about safe programming so it should has been implemented.

My experience says to me that this is bad style:


test := 1;
for (...) {
  if(...) {
    test = 2;
return test


Mutable vars may be initialized mistakenly. We need know exactly that var won't initialized again!

In most cases vars should be read-only by design. It's good style!

I suggest make all var as read-only by default. If need mutable(in least cases) then we will set additional symbol.

For example:

Srt readonly := "foo"
Srt! mutable := "bar"

init(readonly, mutable)

Void init(Str readonly, Str! mutable) {
  readonly = "cat" // Error!
  mutable = "dog" // Ok

Also I suggest to remove const keyword from lang at all. I know that the compiler uses const classes but this flag may to hide to bytecode. If class is not contains mutable fields then set hidden const flag.

Second easy way is allow const for local vars:

Void test(const Str readonly, Str mutable) {
  const Int a := 5;
  a = 3 // error


go4 Thu 14 Sep

I think the Fantom assumes you never make mistake at a local scope.

But the const for local vars is useful for closure. It's difficult to know a closure is mutable or not, until runtime:

Void main()
  Int i := 1
  fun := |->| { echo(i) }

Login or Signup to reply.