如何将构造时代码混合到具有 Scala 特征的类中?

发布于 2024-12-13 18:22:05 字数 232 浏览 2 评论 0原文

我希望所有扩展该特征的类都存储其创建时间(作为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风吹过旳痕迹 2024-12-20 18:22:05

您不能通过特征添加构造函数。

You can't add constructors through traits.

|煩躁 2024-12-20 18:22:05

只需替换 def currentTime 的实现即可生成 org.joda.time.DateTime 实例,并将该特征混合到任何类中。

trait Timestamp {
  private def currentTime = {
    import java.util.Calendar._

    val calendar = getInstance

    def hours = calendar.get(HOUR_OF_DAY)
    def minutes = calendar.get(MINUTE)
    def seconds = calendar.get(SECOND)
    def milliseconds = calendar.get(MILLISECOND)

    hours + ":" + minutes + ":" + seconds + ":" + milliseconds
  }

  final val creationTime = currentTime
}

Just replace the implementation of the def currentTime to result in an org.joda.time.DateTime instance and mix the trait into any class.

trait Timestamp {
  private def currentTime = {
    import java.util.Calendar._

    val calendar = getInstance

    def hours = calendar.get(HOUR_OF_DAY)
    def minutes = calendar.get(MINUTE)
    def seconds = calendar.get(SECOND)
    def milliseconds = calendar.get(MILLISECOND)

    hours + ":" + minutes + ":" + seconds + ":" + milliseconds
  }

  final val creationTime = currentTime
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文