VOOZH about

URL: https://www.geeksforgeeks.org/scala/scala-stateful-object/

⇱ Scala | Stateful Object - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Scala | Stateful Object

Last Updated : 5 Dec, 2022

Stateful Objects are that objects which have changeable members or mutable members, that may vary what transactions or operations were previously performed on the object. For a same operation performed many times, the result outputted may be different from previous result's. It is very common to compare stateful objects with real world objects, where the state of the objects changes over-time. Syntax:

class classname
{
 // declaring some states that are mutable
 var state1
 var state2
 def changestate
 {
 // some operation to change the states of the object
 }
}

When the members of an objects changes its value overtime for certain operation, which are performed on the object. Due to this the statefulness of the object changes that depends on the previously performed operations. Below are some examples to understand stateful object. Examples #1: 

Output :

water in bottle = 3
water left = 2
water left = 1
water left = 0
waterbottle empty fill water

As we can see in the above example state for w.drinkwater changes its result for the same operation to "waterbottle empty fill water" till we fill or update water. The mutable state depends on water which is a variable. Thus we can say that stateful objects are made from vars and not val but this is not true, a class can change its state without containing any vars. For an object that changes its state to another state, the set of operation or the path taken to reach that particular state can be different, but at the end what state is achieved should be same. This is also known as operational equivalence where x & y are different objects but with the same states at the end of different set of operations. Examples #2: 

Output :

player@506e1b77 health is 7
player@506e1b77 health is 5
player@506e1b77 health is 0
Game Over
player@506e1b77 is dead player@4fca772d is winner
Game Over
player@506e1b77 is dead player@4fca772d is winner

Similarly in the above example we can tell that player is a stateful object without looking at the internal working of the class. Because the health cannot be reduced to negative so player has mutable states as the same operation returns different output at different or same inputs.

Comment
Article Tags:

Explore