案例类和案例对象之间的区别? [英] Difference between case class and case object?

查看:69
本文介绍了案例类和案例对象之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Scala和Akka,并在最近的查找中找到了解决方案,我发现类似

I am learning Scala and Akka and in my recent lookup for a solution, I found something like

 case class TotalTaxResult(taxAmount:Double)
 case object TaxCalculationTimeout

两者有什么区别?

我什么时候应该

推荐答案

案例类可以接受参数,因此该案例类的每个实例可以基于它的参数值。另一方面,case对象在构造函数中不使用args,因此只能有一个实例(单例,如常规scala object 是)。

A case class can take arguments, so each instance of that case class can be different based on the values of it's arguments. A case object on the other hand does not take args in the constructor, so there can only be one instance of it (a singleton, like a regular scala object is).

如果发给actor的消息不需要任何区分值,请使用case对象。例如,如果您有一位演员做了一些工作,而您从外面想告诉他去做某事,那么也许您会做这样的事情:

If your message to your actor does not need any value differentiation, use a case object. For instance, if you had an actor that did some work, and you, from the outside, wanted to tell it to do work, then maybe you'd do something like this:

case object DoWork

...

def receive = {
  case DoWork => 
     //do some work here
}

但是如果您想要一些变化在如何完成工作中,您可能需要像这样重新定义消息:

But if you wanted some variation in how the work is done, you might need to redefine your message like so:

case class DoWorkAfter(waitTime:Long)

...

def receive = {
  case class DoWorkAfter(time) =>
    context.system.scheduler.scheduleOnce(time.milliseconds, self, DoWork)

  case DoWork => 
     //do some work here
}

这篇关于案例类和案例对象之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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