我创建了 Value Class
final class Feature(val value: Vector[Double]) extends AnyVal
致
match
在 scala
中反对那个类(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/