何时使用案例类或常规类 [英] When to use case class or regular class

查看:50
本文介绍了何时使用案例类或常规类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些误解,在什么情况下我应该按照最佳实践使用案例类或常规类.我已经阅读了这两个类的差异,但无法想象自己在现实生活中推荐用例或常规类的例子.

I have some misunderstanding in what cases I should use case class or regular class following by best practices. I have already read about differences of both classes but cannot imagine myself real-life examples where is reccommended to use case or regular class.

有人可以向我展示真实的例子,并解释为什么建议这样做而不是其他方式吗?

Could anybody show me real examples with explanation why it's reccommended to do so and not otherwise?

推荐答案

如果您打算使用不可变对象编写纯函数式代码,您最好尝试避免使用常规类.功能范式的主要思想是将数据结构和对它们的操作分离.案例类是具有必要方法的数据结构的表示.数据上的功能应该在不同的软件实体(例如特征、对象)中进行描述.

If you are going to write purely functional code with immutable objects, you should better try avoid using regular classes. The main idea of the functional paradigm is the separation of data structures and operations on them. Case Classes are a representation of a data structure with the necessary methods. Functions on the data should be described in different software entities (e.g., traits, objects).

相反,常规类链接数据和操作以提供可变性.这种方法更接近于面向对象的范式.

Regular classes, on the contrary, link data and operations to provide the mutability. This approach is closer to the object-oriented paradigm.

因此,在以下情况下不要使用案例类:

As a result, do not use Case Classes if:

  1. 您的类带有可变状态.
  2. 您的课程包含一些逻辑.
  3. 您的类不是数据表示,您不需要结构相等.

但是,在这些情况下,您应该真正考虑代码的风格,因为它可能不够实用.

However, in these cases, you should really think about the style of your code because it probably is not functional enough.

这篇关于何时使用案例类或常规类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆