scala - 匹配 Akka 中的值类

标签 scala akka value-class

我创建了 Value Class

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

matchscala 中反对那个类(class):
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 文档提到:

The recommended way to instantiate actor props uses reflection at runtime to determine the correct actor construc- tor to be invoked and due to technical limitations is not supported when said constructor takes arguments that are value classes. In these cases you should either unpack the arguments or create the props by calling the constructor manually:



但不要提及匹配 Value classes
更新

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

收到消息的 Actor :
  def receive = LoggingReceive {
    case Feature(a) =>
      log.info("Got feature {}", a)
    // ....
  }

发送消息的 Actor :
  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
    // ..
  }

最佳答案

由于值类工作方式的性质,您的两个示例都将导致 Feature 的分配。 .一次是由于模式匹配示例中的运行时检查,另一次是由于 receive 的签名这需要 Any作为输入类型。
docs for Value Classes指定(强调我的):

Allocation Summary

A value class is actually instantiated when:

  • a value class is treated as another type.
  • a value class is assigned to an array.
  • doing runtime type tests, such as pattern matching.

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

关于scala - 匹配 Akka 中的值类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42297565/

相关文章:

java - 我应该使用什么数据结构来在恒定时间内从一对变化的值到java中的对象进行查找?

java - 集合中 Scala.Long 和 Java.lang.Long 之间的隐式转换

scala - 值类中的验证

http - Scala海量网址下载

Scala自类型注释与 'with'混合

java - 升级 IntelliJ 后 Play Framework 中的 Controller 出现 InstantiationException

scala - ActorRefs 作为 Akka 中消息的一部分(java.io.NotSerializableException)

Akka 用于持久工作队列

string - 带格式的 Scala 字符串插值,如何更改语言环境?

scala - Scala 中 akka actor 系统内的全局变量