I think a lot of confusion arises because there is no need for closures in popular imperative OO languages like Java which many, if not most, developers are most familiar with. The state is carried in the containing object that every function must have. But for functional or hybrid languages where functions do not necessarily have a containing object, they are vital. In hybrid languages like Scala or Javascript they allow access to state that can be seen by other functions and objects as opposed to state that is contained just within the function's scope without the need of a containing object. This is powerful but dangerous in that you can change the state of these variables and, without great care, they can change in surprising ways. In purely functional languages like Haskell where state is immutable closures are useful to pass around necessary "write once" state with the function with no worries about side effects while ensuring the function has everything it needs to work when necessary.
No comments:
Post a Comment