What does it mean to instantiate a trait?

后端 未结 1 718
名媛妹妹
名媛妹妹 2021-01-02 06:15

I\'m new to Scala and in the Programming Scala book from O\'Reilly the authors show some code that instantiates a trait. Given that traits are somewhat analogous to interfac

相关标签:
1条回答
  • 2021-01-02 07:18

    I'm reasonably new to Scala as well, but I think the example that you have above is creating a new anonymous object (like you can do with Java), and then attaching the Trait to the new anonymous type.

    Since Scala Traits can contain implementation code, you basically get the behavior of the Trait for free, assuming the anonymous class satisfies any requirements of the Trait (like having values set, or defining "abstract" methods).

    So what you are doing here is not instantiating the Trait directly, but rather creating a suitable object for the Trait to attach itself to so you can use the Trait's functionality without needing to define a class that extends the Trait.

    Does that answer your question?

    0 讨论(0)
提交回复
热议问题