本文介绍了如何在Scala中访问复杂的数据结构,同时保持不变性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

调用Scala专家开发者!假设你有一个大的对象代表一个可写的数据存储。你喜欢这种常见的类Java方法:

  val complexModel = new ComplexModel()
complexModel.modify )
complexModel.access(...)

或者你更喜欢:

  val newComplexModel = complexModel.withADifference 
newComplexModel.access(...)

如果你喜欢这个,你有一个客户端访问模型,客户端如何去
知道指向newComplexModel而不是complexModel ?从用户的角度来看,
你有一个可变数据存储。您如何将Scala的重点
与不可变性进行调和?



这样做如何:

  var complexModel = new ComplexModel()
complexModel = complexModel.withADifference
complexModel.access(...)
pre>

这似乎有点像第一种方法,除了它似乎与ADID中的代码将要比modify()中的代码更多的工作,因为它必须创建一个全新的复杂数据对象,而不是修改现有的。 (Do 遇到这个问题,需要做更多的工作才能保留
的不变性?)此外,您现在有一个范围很大的var。



您如何决定最佳策略?您有选择的策略有例外吗?

解决方案

我认为功能的方法是实际上包含所有不同版本的Stream的数据结构和消费者只是想从该流中拉下一个元素。



但我认为在Scala中,这是一个绝对有效的方法,在一个中心的可变参考当您的整个数据结构保持不变时,您的整个数据结构将保持不变。



当数据结构变得更加复杂时,您可能对此问题感兴趣:,请求(并获得回答)如何实际创建不可变数据结构的新更改版本这不是微不足道的。


Calling expert Scala developers! Let's say you have a large object representing a writable data store. Are you comfortable with this common Java-like approach:

val complexModel = new ComplexModel()
complexModel.modify()
complexModel.access(...)

Or do you prefer:

val newComplexModel = complexModel.withADifference
newComplexModel.access(...)

If you prefer that, and you have a client accessing the model, how is the client goingto know to point to newComplexModel rather than complexModel? From the user's perspectiveyou have a mutable data store. How do you reconcile that perspective with Scala's emphasison immutability?

How about this:

var complexModel = new ComplexModel()
complexModel = complexModel.withADifference
complexModel.access(...)

This seems a bit like the first approach, except that it seems the code inside withADifference is going to have to do more work than the code inside modify(), because it has to create a whole new complex data object rather than modifying the existing one. (Do you run into this problem of having to do more work in trying to preserveimmutability?) Also, you now have a var with a large scope.

How would you decide on the best strategy? Are there exceptions to the strategy you would choose?

解决方案

I think the functional way is to actually have Stream containing all your different versions of your datastructure and the consumer just trying to pull the next element from that stream.

But I think in Scala it is an absolutely valid approach to a mutable reference in one central place and change that, while your whole datastructure stays immutable.

When the datastructure becomes more complex you might be interested in this question: Cleaner way to update nested structures which asks (and gets answered) how to actually create new change versions of an immutable data structure that is not trivial.

这篇关于如何在Scala中访问复杂的数据结构,同时保持不变性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 18:18