aij
aij

Reputation: 6501

Does scala have shortcuts for functional objects?

I'm writing class in Scala and want to write some update methods that will return a modified version of the original object. I want the class to continue to be immutable of course.

Of course I could do it by explicitly creating a new object of the appropriate type each time, as is done in this example, however that breaks in the face of inheritance since calling the methods on an instance of the subclass would instead return an instance of the superclass.

FWIW, I come from the land of OCaml which has special syntax to support functional objects. For an example, see here

So, does Scala have an equivalent for {< x = y >} in OCaml?

Upvotes: 4

Views: 134

Answers (1)

waffle paradox
waffle paradox

Reputation: 2775

I'm not familiar with the concept of "functional objects" in ocaml, but I think case classes may have what you need. For a simple use case, they provide some nice syntax and convenient functions like copy:

scala> case class Foo(a: Int, b: Int)
defined class Foo

scala> val f = Foo(1, 2)
f: Foo = Foo(1,2)

scala> val g = f.copy(a = 2)
g: Foo = Foo(2,2)

However it does come with some important limitations (like lack of inheritance). See this page for more info: http://www.scala-lang.org/old/node/107 and this thread for why it's a bad idea to inherit from case classes: What is *so* wrong with case class inheritance?

Upvotes: 5

Related Questions