如何定义更简洁的scala函数
我正在使用 akka 库并提供一个部分函数,以便由参与者在运行时通过热交换来实现。
akka 热交换采用 PartialFunction[Any, Unit] 形式的参数。我的定义如下:
class Fake1Reader extends AbstractReader {
def read: PartialFunction[Any, Unit] = {
case readingRequest: ReadingRequest => {
var reading: Reading = new ReadingImpl(readingRequest.getResourceId, "payload",
Calendar.getInstance.getTime,
readingRequest.getfrequency, readingRequest.getMappingName,
readingRequest.getClassificationType,
readingRequest.getReadingRequestId)
sendConsumeMessage(reading)
}
}
}
所以为了使用这个函数,我必须提供一个新的 Fake1Reader().read。
有没有更简洁的方法使用 apply 或扩展 Function 或 PartialFunction 来执行此类?
I am using the akka library and supplying a partial function to be implemented by an actor at runtime via a hot swap.
The akka hot swap takes an argument in the form PartialFunction[Any, Unit]. I have defined mine as the following:
class Fake1Reader extends AbstractReader {
def read: PartialFunction[Any, Unit] = {
case readingRequest: ReadingRequest => {
var reading: Reading = new ReadingImpl(readingRequest.getResourceId, "payload",
Calendar.getInstance.getTime,
readingRequest.getfrequency, readingRequest.getMappingName,
readingRequest.getClassificationType,
readingRequest.getReadingRequestId)
sendConsumeMessage(reading)
}
}
}
so in order to use this function I have to supply a new Fake1Reader().read.
Is there any more concise way of doing this class using apply or extending Function or PartialFunction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的
AbstractReader
是无状态的,您可以定义object
而不是class
以避免每次使用时创建不必要的对象,并将函数放置在那里作为不可变的val
的。此外,伴随对象
akka.actor.Actor
将类型Receive
定义为PartialFunction[Any, Unit]
的别名,因此您可以编写您的部分功能如下:用法:
If your
AbstractReader
is stateless, you can defineobject
instead ofclass
to avoid unnecessary object creation on every usage,and place your functions there as immutableval
's.Also, companion object
akka.actor.Actor
defines typeReceive
as an alias forPartialFunction[Any, Unit]
, so you can write your partial functions like this:usage:
顺便说一句,这减少了重复的苦差事:
As a side note, this reduces the sheer drudgery of repetition: