Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Programming in Scala > Chapter 18: Stateful Objects - Pg. 361

Chapter 18 Stateful Objects In previous chapters, we put the spotlight on functional (immutable) objects. We did so because the idea of objects without any mutable state deserves to be better known. However, it is also perfectly possible to define objects with mutable state in Scala. Such stateful objects often come up naturally when you want to model objects in the real world that change over time. This chapter explains what stateful objects are, and what Scala provides in terms of syntax to express them. The second part of this chapter intro- duces a larger case study on discrete event simulation, which involves state- ful objects as well as building an internal domain specific language (DSL) for defining digital circuits to simulate. 18.1 What makes an object stateful? You can observe the principal difference between a purely functional object and a stateful one even without looking at the object's implementation. When you invoke a method or dereference a field on some purely functional object, you will always get the same result. For instance, given a list of characters: val cs = List('a', 'b', 'c') an application of cs.head will always return 'a' . This is the case even if there is an arbitrary number of operations on the list cs between the point where it is defined and the point where the access cs.head is made. For a stateful object, on the other hand, the result of a method call or field access may depend on what operations were previously performed on the 361