scala – 匹配Akka中的Value Classes

我创造了价值等级

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

要在scala中匹配该类:

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

这是正常的,但在Akka中,与上面相同的类,在接收方法中,这是行不通的:

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

当我执行代码时,虽然我正在发送一个功能,但正在执行的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类匹配的任何内容

更新

感谢YuvalItzchakov的帮助.演员的代码如下:

收到消息的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
    // ..
  }

最佳答案 由于值类的工作方式的性质,您的示例都将导致功能的分配.一旦由于模式匹配示例中的运行时检查,另一个由于接收的签名而需要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 [_]类型,则意味着您实际从代码中的某个位置传递具体向量.

点赞