Does scala have shortcuts for function objects?

I am writing a 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 stay the same, of course.

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

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

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

+4
source share
1 answer

I am not familiar with the concept of "functional objects" in ocaml, but I think class classes may have what you need. For a simple use case, they provide good syntax and convenient functions, such as 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 has some important limitations (for example, lack of inheritance). See this page for more information: http://www.scala-lang.org/old/node/107 and this thread for why is it a bad idea to inherit from case classes: What is * so * wrong with case class inheritance?

+5
source

All Articles