【问题标题】:Matching against Value Classes in Akka匹配 Akka 中的值类
【发布时间】:2017-07-06 22:59:49
【问题描述】:

我创建了Value Class

final class Feature(val value: Vector[Double]) extends AnyVal

match 反对scala 中的那个类:

val d = new Feature(Vector(1.1))
s match {
  case a:Feature => println(s"a:feature, $a")
  case _ => println("_")
}

这可以正常工作,但在 Akka 中,具有上述相同的类,在 receive 方法中这是行不通的:

  def receive = LoggingReceive {
    case a:Feature =>
      log.info("Got Feature: {}", a)
    case _ => println("_")
  }

当我执行代码时,虽然我发送的是Feature,但正在执行的case 语句是case _ => println("_"),但是,如果我将代码更改为:

  def receive = LoggingReceive {
    case a:Feature =>
      log.info("Got Feature: {}", a)
    case b:Vector[_] =>
      log.info("GOT FEATURE")
    case _ => println("_")
  }

case b:Vector[_] 被执行。

Akka 文档提到:

推荐的实例化actor props 的方法是在运行时使用反射来确定正确的actor 构造 当所述构造函数采用以下参数时,不支持要调用的 tor 并且由于技术限制 价值类别。在这些情况下,您应该解压缩参数或通过调用构造函数创建道具 手动:

但不要提及匹配Value classes

更新

感谢 YuvalItzchakov 的帮助。 Actor的代码如下:

接收消息的Actor:

  def receive = LoggingReceive {
    case Feature(a) =>
      log.info("Got feature {}", a)
    // ....
  }

发送消息的演员:

  def receive = LoggingReceive {
    // ..
    case json: JValue =>
      log.info("Getting json response, computing features...")
      val features = Feature(FeatureExtractor.getFeatures(json))
      log.debug(s"Features: $features")
      featureListener.get ! features
    // ..
  }

【问题讨论】:

    标签: scala akka value-class


    【解决方案1】:

    由于值类工作方式的性质,您的两个示例都将导致分配Feature。一次是由于您的模式匹配示例中的运行时检查,另一次是由于receive 的签名需要Any 作为输入类型。

    正如docs for Value Classes 指定(强调我的):

    分配汇总

    值类在以下情况下实际实例化:

    • 值类被视为另一种类型
    • 一个值类被分配给一个数组。
    • 进行运行时类型测试,例如模式匹配

    这意味着如果您看到 Vector[_] 类型,这意味着您实际上是从代码中的某个位置传递了一个具体的向量。

    【讨论】:

    • 谢谢!所以,您建议我删除 Value 类并与 Vector[Double] 匹配?
    • @algui91 我建议不要扩展AnyVal 并匹配Feature。匹配更高种类的类型不是一个好主意,因为它们会被类型擦除,并且您总是希望将它们包装在一个额外的案例类中。
    • "你通过tell向actor发送Feature,所以运行时不会分配Feature"为什么不是“一个值类被视为另一种类型”的情况,即@ 987654329@?
    • @AlexeyRomanov 你完全正确,我忽略了receive 上的Any 并且无法在本地复制它。查看生成的 Scala 代码,编译器仍然使用 Feature 包装消息。
    猜你喜欢
    • 2014-01-08
    • 2014-03-05
    • 2021-05-13
    • 2018-06-20
    • 2018-04-20
    • 2018-02-16
    • 1970-01-01
    • 2019-09-29
    • 2018-03-12
    相关资源
    最近更新 更多