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 interfaces in Java (although I know traits are implemented as classes in the byte code), what does it mean to instantiate a trait, and what would be an appropriate use case / design pattern for this?
E.g.:
scala> val x = new T1 with T2 { type z = String val v: z = "Z" }
x: java.lang.Object with T1 with T2{type z = String; def zv: this.z} = $anon$1@9d9347d
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With