如何将构造时代码混合到具有 Scala 特征的类中?
我希望所有扩展该特征的类都存储其创建时间(作为 org.joda.time.DateTime 实例)。该特征将 def dt : DateTime
定义为 getter。我还可以定义代码来获取特征中的时间戳(旨在在构造时运行)吗?
更新:我想我已经想到如何在不处理构造函数的情况下实现特定任务(只需将 dt 定义为 val 并将其设置为新的 DateTime,也许这会起作用) ,不过标题中的问题还是很有趣。
I want all the classes extending the trait to store their creation time (as a org.joda.time.DateTime
instance). The trait defines def dt : DateTime
as a getter. Can I also define the code to take the timestamp (which is intended to run at construction time) in the trait?
UPDATE: I think I've came to an idea how to implement the particular task without dealing with constructors (just define dt
as a val and set it to a new DateTime, maybe this is going to work), but the question in the title is still interesting.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能通过特征添加构造函数。
You can't add constructors through traits.
只需替换
def currentTime
的实现即可生成org.joda.time.DateTime
实例,并将该特征混合到任何类中。Just replace the implementation of the
def currentTime
to result in anorg.joda.time.DateTime
instance and mix the trait into any class.