#2093 Copy and Mutate Const Object

andy Sun 3 Feb 2013

Doesn't look like we support this quite yet at all. But we need an easy way to mutate a const object, which returns a new copy. Looks like @brian made an initial proposal in #492 - but we didn't follow up. This still seems like a plausible design - assuming no implementation hurdles.

const class Foo
{
  new make(|This| f) { f(this) }
  const Int a := 10 
  const Int b
}

orig := Foo { it.a=12; it.b=5 }
copy := orig { it.a=44 }

SlimerDude Tue 19 Feb 2013

I'm not so keen on the shortcut version. I'd prefer if the cloning was kept explicit and more readable:

orig := Foo { it.a=12; it.b=5 }
copy := orig.with() { it.a=44 }

brian Wed 6 Mar 2013

I think you have to start with how clone works, which I always thinks gets messy with regards to deep vs shallow clone. But in the case of const classes deep vs shallow shouldn't matter since the entire thing is immutable. I think the reason we never really bit this off is because it is probably mixed up with some of the stuff we talked about for "struct classes" that have auto-generated constructor, equals, hash, etc.

Jens Thu 7 Mar 2013

I think it would be best with a new special method on const classes. Reusing with makes it a little too implicit. Like this:

foo2 := foo1.copy { it.a = 12 }

Also, const classes will often have other const classes as members. Updating those is when it really starts to get messy, and it would be nice if that case also got handeled:

foo2 := foo1.copy { it.foo.a = 12 }

Also:

"struct classes" that have auto-generated constructor, equals, hash, etc

That sounds like a great idea! Maybe something Lombokish?

Jens Sat 31 Aug 2013

Apparently Scala has a similar feature for their case classes:

http://daily-scala.blogspot.se/2010/01/case-classes-in-28.html

Login or Signup to reply.