Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to instantiate a trait?

Tags:

scala

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
like image 866
Jamie Forrest Avatar asked May 27 '11 17:05

Jamie Forrest


1 Answers

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?

like image 173
ckramer Avatar answered Oct 09 '22 10:10

ckramer